![](/img/trans.png)
[英]AutoLayout Constraints on UITableViewCell of UITableViewCellStyleSubtitle
[英]where to create autolayout constraints for subclassed 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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.