我正在尝试在每个自定义单元格(继承自NSLayoutConstraint
)中设置UITableViewCell
,而不是在UIViewController
中指定它们,以避免因为每个自定义约束而使其混乱细胞类型。
问题在于我无法找到单元生命周期的适当部分来创建布局约束(我尝试layoutSubviews()
和awakeFromNib()
),但它们都在单元的生命周期中被调用得太早,当其superview
尚未定义时 - 会导致此错误:
约束必须包含第一个布局项
由于UITableViewCell
没有像viewDidLoad()
那样的UIViewController
方法,如何在单元格中定义布局约束呢?
layoutSubviews()
自定义UITableViewCell
:
- (void) layoutSubviews {
self.translatesAutoresizingMaskIntoConstraints = false;
[[NSLayoutConstraint constraintWithItem: self.attributeNameLabel
attribute: NSLayoutAttributeLeading
relatedBy: NSLayoutRelationEqual
toItem: self.contentView
attribute: NSLayoutAttributeLeading
multiplier: 1
constant: 3] setActive:true];
[[NSLayoutConstraint constraintWithItem: self.attributeNameLabel
attribute: NSLayoutAttributeTop
relatedBy: NSLayoutRelationEqual
toItem: self.contentView
attribute: NSLayoutAttributeTop
multiplier: 1
constant: 3] setActive:true];
[[NSLayoutConstraint constraintWithItem: self.attributeNameLabel
attribute: NSLayoutAttributeRight
relatedBy: NSLayoutRelationEqual
toItem: self.contentView
attribute: NSLayoutAttributeRight
multiplier: 1
constant: 3] setActive:true];
[[NSLayoutConstraint constraintWithItem: self.attributeNameLabel
attribute: NSLayoutAttributeBottom
relatedBy: NSLayoutRelationEqual
toItem: self.contentView
attribute: NSLayoutAttributeBottom
multiplier: 1
constant: 3] setActive:true];
}
UIViewController
中的初始化示例:
- (UITableViewCell *)tableView:(UITableView *)view cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
if (indexPath.row % 2 == 0) {
cell = [[CustomCell1 alloc] init];
} else if (indexPath.row % 2 == 1) {
cell = [[CustomCell2 alloc] init];
} else if (...) {
...
}
return cell;
}
答案 0 :(得分:2)
尝试制作
self.attributeNameLabel.translatesAutoresizingMaskIntoConstraints = NO;
对于每个标签而不是contentView
转换它们就像它对我有用
这样做
- (void)awakeFromNib {
// Initialization code
[super awakeFromNib];
UILabel*ddd = [UILabel new];
ddd.text = @"adsbcujklasdcbaksci";
ddd.translatesAutoresizingMaskIntoConstraints = NO ;
[self.contentView addSubview:ddd];
NSLayoutConstraint*ss1 = [NSLayoutConstraint constraintWithItem: ddd
attribute: NSLayoutAttributeCenterX
relatedBy: NSLayoutRelationEqual
toItem: self.contentView
attribute: NSLayoutAttributeCenterX
multiplier: 1 constant: 3] ;
NSLayoutConstraint*ss2 = [NSLayoutConstraint constraintWithItem: ddd
attribute: NSLayoutAttributeCenterY
relatedBy: NSLayoutRelationEqual
toItem: self.contentView
attribute: NSLayoutAttributeCenterY
multiplier: 1 constant: 3] ;
[self.contentView addConstraints:@[ss1,ss2]];
[self layoutSubviews];
[self layoutIfNeeded];
}