【发布时间】:2014-02-08 00:48:26
【问题描述】:
我正在使用子类 UITableViewCell,我需要在使用自动布局时将 UILabel 的文本与左上角对齐。我意识到阅读 sizeToFit 真的不应该与 Auto Layout 一起使用,我想避免它,并以某种方式使用约束。基本上,每次重复使用单元格时都会重置标签的文本,因此在重复使用时需要动态调整大小。
这是子类单元格内的惰性初始化器标签:
- (UILabel *)commentsLabel {
if (_commentsLabel == nil) {
_commentsLabel = [[UILabel alloc] init];
[_commentsLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
_commentsLabel.numberOfLines = 0;
_commentsLabel.lineBreakMode = NSLineBreakByWordWrapping;
_commentsLabel.preferredMaxLayoutWidth = 100;
}
return _commentsLabel;
}
在标签上设置了自动布局约束(cmetsLabel 是在 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。
ETA:尝试在现有垂直约束线内设置高度约束:
喜欢这里的建议:Dynamically change UILabel width not work with autolayout
在垂直约束线上方制作:
-[commentsLabel(>=30@900)]-
我弄乱了高度值和优先级值,没有任何改变。
ETA:取得了一些进展,我认为这与标签的底部填充有关,尝试了这个,有些标签正确对齐有些没有:
->=commentsToBottomPadding-
【问题讨论】:
-
你看过这篇文章吗? stackoverflow.com/questions/18746929/…
标签: ios iphone objective-c uitableview autolayout