1. 程式人生 > >tableviewheaderview 高度自適應

tableviewheaderview 高度自適應

reat sco uitable cgrect label 約束 自適應 any dem

完全使用約束 使tableviewheaderview 的高度自適應,以後再也不用去計算headerview的高度後再去改變高度了,

demo代碼:

#import "ViewController.h"
#import "Masonry.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation ViewController

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
return 10; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; cell.textLabel.text = [NSString stringWithFormat:@"------------%ld
",indexPath.row]; return cell; } - (void)viewDidLoad { [super viewDidLoad]; UILabel *testlable = [[UILabel alloc]init]; testlable.numberOfLines = 0; testlable.font = [UIFont systemFontOfSize:12]; UIView *headerview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10
)]; [headerview addSubview:testlable]; UITableView *tableview = [[UITableView alloc]init]; tableview.delegate = self; tableview.dataSource = self; tableview.rowHeight = 50; [self.view addSubview:tableview]; tableview.tableHeaderView = headerview; [testlable mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.mas_equalTo(headerview); }]; [headerview mas_makeConstraints:^(MASConstraintMaker *make) { make.width.mas_equalTo(self.view.frame.size.width); }]; [tableview mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.mas_equalTo(self.view); }]; testlable.text = @"測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字測試文字==="; [tableview layoutIfNeeded]; tableview.tableHeaderView = headerview; NSLog(@"----------headerview_frame:%@-------testlable_frame:%@",NSStringFromCGRect(headerview.frame),NSStringFromCGRect(testlable.frame)); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end

tableviewheaderview 高度自適應