试图让我的Table View头根据三个标签动态调整大小,其中一个标签具有动态内容。看起来很简单,但运气不太好。任何建议都非常感谢!
在这篇文章here之后,将我的约束设置为:



我的代码很简单。主计长:
- (void)viewDidLoad {
[super viewDidLoad];
[self loadViewsWithParseObject];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)loadViewsWithParseObject {
if (TRUE) {
self.postView.backgroundColor = [UIColor blueColor];
self.postLabel.backgroundColor = [UIColor redColor];
self.addCommentTextView.backgroundColor = [UIColor orangeColor];
self.addCommentButton.backgroundColor = [UIColor purpleColor];
}
// assign postLabel.text
self.postLabel.text = [self.postObject objectForKey:@"postText"];
[self sizeHeaderToFit];
NSLog(@"postView height = %f", self.postView.frame.size.height);
}
- (void)sizeHeaderToFit
{
UIView *header = self.tableView.tableHeaderView;
[header setNeedsLayout];
[header layoutIfNeeded];
CGFloat height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
CGRect frame = header.frame;
frame.size.height = height;
header.frame = frame;
self.tableView.tableHeaderView = header;
}这就是输出的样子(首先是三行post,其中post标签显示正确,但缺少“添加注释”标签;第二,长lorem ipsem段落,但只有一行显示正确,同样,“添加注释”标签也被否决):


发布于 2015-06-02 05:13:17
之所以会发生这种行为,是因为UITextView没有preferredMaxLayoutWidth属性,因此其intrinsicContentSize大小无效。
您需要手动计算addCommentTextView的内容高度,尝试如下:
- (void)sizeHeaderToFit
{
UIView *header = self.tableView.tableHeaderView;
[header setNeedsLayout];
[header layoutIfNeeded];
CGFloat height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
CGFloat textViewHeight = [self.addCommentTextView sizeThatFits:CGSizeMake(self.addCommentTextView.bounds.size.width, CGFLOAT_MAX)].height;
height += textViewHeight;
CGRect frame = header.frame;
frame.size.height = height;
header.frame = frame;
self.tableView.tableHeaderView = header;
}编辑:将preferredMaxLayoutWidth设置为将解决此问题的postLabel。
self.postLabel.preferredMaxLayoutWidth = self.postLabel.bounds.size.width;
CGFloat height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
CGFloat textViewHeight = [self.textView sizeThatFits:CGSizeMake(self.textView.bounds.size.width, CGFLOAT_MAX)].height;
height += textViewHeight;preferredMaxLayoutWidth 当应用布局约束时,此属性会影响标签的大小。在布局期间,如果文本超出此属性指定的宽度,则附加文本将流到一个或多个新行,从而增加标签的高度。
https://stackoverflow.com/questions/30586733
复制相似问题