我正在使用一个子类化的 UITableViewCell,我需要在使用自动布局时将 UILabel 的文本对齐到左上角。我意识到阅读 sizeToFit 真的不应该与自动布局一起使用,我想避免它,并以某种方式使用约束。基本上,标签的文本在每次重复使用单元格时都会重置,因此大小调整需要在重复使用时动态调整。
这是子类单元格中的延迟初始化器标签:
- (UILabel *)commentsLabel {
if (_commentsLabel == nil) {
_commentsLabel = [[UILabel alloc] init];
[_commentsLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
_commentsLabel.numberOfLines = 0;
_commentsLabel.lineBreakMode = NSLineBreakByWordWrapping;
_commentsLabel.preferredMaxLayoutWidth = 100;
}
return _commentsLabel;
}
在标签上设置了自动布局约束(commentsLabel 是添加到 cell 子类上的 self.customView 的 subview ):
[self.customView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-locationToTopPadding-[locationLabel(locationHeight)]-locationToCommentsPadding-[commentsLabel]-commentsToBottomPadding-|"
options:0
metrics:@{
@"locationToTopPadding":@(locationToTopPadding),
@"locationHeight":@(locationHeight),
@"locationToCommentsPadding":@(locationToCommentsPadding),
@"commentsToBottomPadding":@(commentsToBottomPadding)
}
views:viewsDictionary]];
[self.customView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[thumbnailImageView]-[commentsLabel]-|"
options:0
metrics:@{@"commentsWidth":@(commentsWidth)}
views:viewsDictionary]];
设置只是:
self.commentsLabel.preferredMaxLayoutWidth = 100;
尽管大多数答案中都提到了这一点,但似乎不起作用。
目前已经实现,但没有看到任何结果。 UILabel sizeToFit doesn't work with autolayout ios6
我试过的另一个答案。 UILabel sizeToFit only works with AutoLayout turned off
我觉得除了上面的约束之外,我只缺少 1 个可以添加的约束,但我尝试添加的编程约束不起作用或抛出异常。我完全在代码中工作,没有 xib。
预计到达时间:尝试在现有垂直限制线内设置高度限制:
喜欢这里的建议:Dynamically change UILabel width not work with autolayout
在上面的垂直约束线中制作:
-[commentsLabel(>=30@900)]-
我弄乱了高度值和优先级值,但没有任何改变。
ETA:取得了一些进展,我认为这与标签的底部填充有关,尝试过这个并且一些标签正确对齐有些不是:
->=commentsToBottomPadding-
最佳答案
如果其他人遇到与 UITableViewCell 和动态更改的自定义标签相同的问题时的解决方案:
-[commentsLabel]->=yourBottomPadding-
把它放在垂直约束中
设置文本后在 viewController 中调用它:
[cell updateConstraints];
关于ios - UITableViewCell 单元重用和 UILabel 自动布局动态调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21207078/