整理一下:tableHeaderView

整理一下:tableHeaderView_第1张图片
图片
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.mas_equalTo(UIEdgeInsetsMake(20, 0, 0, 0));
}];

//底部bgView

 self.bgView  = [[UIView  alloc]init];
 self.bgView.backgroundColor = [UIColor greenColor];

//放循环滚动视图
#define HeaderViewHeight 100
self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,   HeaderViewHeight)];
self.headerView.backgroundColor = [UIColor redColor];
[self.bgView addSubview:self.headerView];

//最下面的展示文字
_content = [UILabel new];
_content.numberOfLines = 0;
_content.font = [UIFont systemFontOfSize:15];
self.content.text = @"有这么一种需求,在列表顶端显示一些别样的数据,而这个别样的数据则  需要通过一个别样的 View 来展现,它便是 UITableView 的 tableHeaderView。倘若 tableHeaderView 里的内容很固定,高度不要随着内容的不同而改变,这样还好。如果,高度是需要动态改变的,某些人(比如我)可能就会遇到这样一个难题有这么一种需求,在列表顶端显示一些别样的数据,而这个别样的数据则需要通过一个别样的 View 来展现,它便是 UITableView 的 tableHeaderView。倘若 tableHeaderView 里的内容很固定,高度不要随着内容的不同而改变,这样还好。如果,高度是需要动态改变的,某些人(比如我)可能就会遇到这样一个难题";
[self.bgView addSubview:_content];
//自己封装的计算文字的size(展示时的字体font要和计算时的font一样才准确)
CGFloat height = [self getLabelSize:self.content.text withFontSize:[UIFont systemFontOfSize:15] width:self.view.frame.size.width];
_content.frame = CGRectMake(0, HeaderViewHeight, self.view.frame.size.width, height);
CGRect newFrame = self.bgView.frame;
newFrame.size.height = newFrame.size.height+height+HeaderViewHeight;

 self.bgView.frame = newFrame;
 [self.tableView setTableHeaderView:self.bgView];
[self.tableView beginUpdates];
[self.tableView setTableHeaderView:self.bgView];
[self.tableView endUpdates];

}

计算文字高度的方法:

-(CGFloat)getLabelSize:(NSString *)string withFontSize:(UIFont *)font width:(CGFloat)width {
  CGSize textSize = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
  return textSize.height;
}

你可能感兴趣的:(整理一下:tableHeaderView)