使用Masonry约束tableHeaderView,解决错位问
2016-07-24 本文已影响309人
loyt
有时候需要往tableHeaderView上添加多个控件,使用Masonry约束更加方便,尤其是控件中的内容不固定时,高度也需要改变,但是在使用过程中发现一些问题,tableHeaderView会把cell的内容覆盖.
遮挡cell直接上代码
-(void)setupTableHeaderView{
UIView *myTableHeaderView = [[UIView alloc] init];
myTableHeaderView.backgroundColor = [UIColor purpleColor];
self.myTableHeaderView = myTableHeaderView;
[myTableHeaderView addSubview:self.myImageView];
[myTableHeaderView addSubview:self.myContentLabel];
[self.myImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(myTableHeaderView).mas_offset(5);
make.centerX.mas_equalTo(myTableHeaderView);
make.size.mas_equalTo(CGSizeMake(100, 100));
}];
[self.myContentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(self.myImageView.mas_bottom).mas_offset(5);
make.width.mas_equalTo(myTableHeaderView);
make.bottom.mas_equalTo(myTableHeaderView).mas_offset(-5);
}];
[self.tableView beginUpdates];
[self.tableView setTableHeaderView:myTableHeaderView];
[self.tableView endUpdates];
//下面这部分很关键,重新布局获取最新的frame,然后赋值给myTableHeaderView
[myTableHeaderView setNeedsLayout];
[myTableHeaderView layoutIfNeeded];
CGSize size = [myTableHeaderView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
CGRect headerFrame = myTableHeaderView.frame;
headerFrame.size.height = size.height;
myTableHeaderView.frame = headerFrame;
self.tableView.tableHeaderView = myTableHeaderView;
}
完美解决