ios – 在哪裡為子類的uitableviewcell建立自動佈局約束?
我正在嘗試使用autolayout來建立一個uitableviewcell子類,並且我會欣賞一些關於使用佈局約束建立程式碼的方法的建議.我一直在搜尋,並且在ViewDidLoad方法中新增子檢視後,我發現所有有關新增約束的資訊.據我所知,viewDidLoad不是一個uitableviewcell子類的選項.
我正在使用介面構建器來建立一個自定義單元格,並在我的程式碼中動態分配它.沒有什麼特別的…我分類uitableviewcell,所以我可以新增一個定製的uiview到單元格.再次,沒有什麼特別的地球破碎…我的困難來了,當我嘗試定位我的定製uiview相對於我新增到介面構建器中的單元格的標籤.
這是建立自定義uiview並將其新增到單元格內容檢視的程式碼:
- (id)initWithCoder:(NSCoder *)decoder { if ((self = [super initWithCoder:decoder])) { [self initSelf]; } return self; } - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { [self initSelf]; } return self; } - (void) initSelf { // Initialization code _badgeLabel = @""; if (!_customBadge) { _customBadge = [CustomBadge customBadgeWithString:self.badgeLabel]; } // hide the badge until needed self.customBadge.hidden = YES; // add badge to the cell view hierarchy [self.customBadge setTranslatesAutoresizingMaskIntoConstraints:NO]; [self.customBadge setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal]; [self.customBadge setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical]; [self.contentView addSubview:self.customBadge]; }
如果我把約束程式碼放在initSelf結尾沒有任何反應.我的_customBadge的位置保持在其預設值.當我在layoutSubviews中放置約束程式碼時,應用定位;但我很確定這是錯誤的地方.以下是程式碼:
- (void) layoutSubviews { [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.customBadge attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.competence attribute:NSLayoutAttributeRight multiplier:1.0 constant:-14.0]]; [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.customBadge attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.competence attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]]; [super layoutSubviews]; }
有誰能告訴我這個程式碼應該去哪裡?當然,每當佈局發生時,我都會建立重複約束.
謝謝
您將需要更新約束:
-(void)updateConstraints{ // add your constraints if not already there [super updateConstraints]; }
將檢視新增到superview之後,需要呼叫[self setNeedsUpdateConstraints]才能開始使用它們.通過這樣做,渲染執行時將在適當的時間呼叫updateConstraints.
http://stackoverflow.com/questions/15894415/where-to-create-autolayout-constraints-for-subclassed-uitableviewcell