TableView标题AutoLayout

时间:2015-06-02 03:17:32

标签: ios uitableview autolayout uistoryboard

尝试让我的Table View标头根据三个标签动态调整大小,其中一个标签具有动态内容。看起来很简单,但没有太多运气。任何建议都非常感谢!

在发布此帖here之后,请设置我的约束:enter image description here

enter image description here

enter image description 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;
}

这是输出的样子(首先是三行帖子,其中帖子标签正确显示但是'添加评论'标签丢失;第二个是长lorem ipsem段但只有一行显示正确,同样'添加评论'标签被驳回):

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

出现这种情况是因为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
  布局约束时,此属性会影响标签的大小   适用于它。在布局期间,如果文本超出宽度   由此属性指定,附加文本将流向一个或   更多新线,从而增加标签的高度。