我整天都在寻找这个问题的解决方案。我正在尝试让我的 UILabels 根据tableViewHeaderView
内文本的长度自动调整自己的大小。通常,将我的 UILabels 放在 UIView 中,我会为 UILeu 设置顶部、前导和尾随约束,它会像我想要的那样工作。但是,我无法在tableViewHeaderView
内工作.我能够设置顶部和前导约束,但我的尾随约束似乎不起作用。文本超出屏幕宽度。
将 preferredMaxLayoutWidth
属性设置为数字可以解决问题,但我不想对其进行硬编码。
如果我错了,请纠正我,但是设置前导和尾随约束应该能够为我提供视图的宽度,不是吗?然后我可以用该值设置preferredMaxLayoutWidth
。但该值是 2403,比屏幕宽度长得多。
还有其他人经历过吗?
#import "CustomTableViewHeader.h"
@implementation ReplyHeader{
UILabel *questionLabel;
}
questionLabel = [[UILabel alloc]init];
questionLabel.text = @"SAMPLE TEXT: I had a question about how I can be a better human being using your method. I belive it is an integral part of what it means to be a human so I want to learn more if you are able give more details about it. I also found that what you said about the dogs out there is very cool and would love to learn more about that.";
questionLabel.font = [UIFont fontWithName:@"AvenirNext-Regular" size:17];
questionLabel.lineBreakMode = NSLineBreakByWordWrapping;
questionLabel.numberOfLines = 0;
questionLabel.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:questionLabel];
约束
[self addConstraint:[NSLayoutConstraint constraintWithItem:questionLabel attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0f constant:5.0f]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:questionLabel attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:-5.0f]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:questionLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0f constant:10]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:questionLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0f constant:-10]];
更新视图
- (void)viewDidLayoutSubviews
{
questionLabel.preferredMaxLayoutWidth = questionLabel.frame.size.width;
[self layoutIfNeeded];
}
UITableView与AutoLayout不相处。页眉和页脚都继承了这个问题。您可能已经知道,UITableViews是花哨的UIScrollViews。如果您曾经尝试过使用滚动视图,许多元素和自动布局,则必须知道它不能很好地工作。它滞后。这就是UITableView重用单元格的原因。它提高了性能,并且他们不使用自动布局。
你应该尝试类似的东西
// with this you will get the most compressed size for your view if the constraints properly define it's size
CGFloat height = [footer systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
footer = CGRectMake(CGRectGetMinX(view.frame), CGRectGetMinY(footer.frame), CGRectGetWidth(footer.bounds), height);
// This will tell the layout engine to ignore the view and not try to resize it
view.autoresizingMask = UIViewAutoresizingNone;
self.tableView.tableFooterView = footer;