嘗試在項(xiàng)目中用masonry布局tableView的頭部。
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section == 0) {
UIView *headerView = [[UIView alloc] init];
[headerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.LoginWaytableView.mas_top);
make.left.equalTo(self.LoginWaytableView.mas_left);
make.right.equalTo(self.LoginWaytableView.mas_right);
make.height.equalTo(@200);
}];
UIImageView *imagerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"景.jpg"]];
[imagerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(headerView.mas_top).with.offset(10);
make.left.equalTo(headerView.mas_left).with.offset(100);
make.right.equalTo(headerView.mas_right).with.offset(-100);
make.height.equalTo(headerView.mas_height).multipliedBy(0.5);
}];
UILabel *passwordLabel = [[UILabel alloc] init];
passwordLabel.text = @"密碼登錄";
passwordLabel.textColor = [UIColor blackColor];
[passwordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(imagerView.mas_top).with.offset(10);
make.left.right.equalTo(imagerView);
make.bottom.equalTo(headerView.mas_bottom).with.offset(10);
}];
[headerView addSubview:imagerView];
[headerView addSubview:passwordLabel];
return headerView;
}
return nil;
}
結(jié)果報(bào)錯(cuò)如下:
***
Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'couldn't find a common superview for
<UIView: 0x7fecaef1edc0; frame = (0 0; 0 0); layer = <CALayer: 0x6080002301a0>>
and <UITableView: 0x7fecb00d7000;
frame = (0 64; 375 603); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x600000258de0>;
layer = <CALayer: 0x600000234a20>; contentOffset: {0, -64}; contentSize: {375, 842}>'
*** First throw call stack:
崩潰原因大致意思是說(shuō),這個(gè)UIView和UITableView沒(méi)有一個(gè)共同的父View。
得出使用自動(dòng)布局autoLayout(Masonry基于約束autoLayout)需要兩個(gè)View擁有一個(gè)共同的父View。很明顯,headerView 和 self.LoginWayTableView兩個(gè)View在目前這個(gè)tableView的代理函數(shù)中還沒(méi)有共同的父View。因?yàn)閔eaderView還沒(méi)有加載在self.LoginWayTableView上面。只有當(dāng)此函數(shù)執(zhí)行結(jié)束的時(shí)候才被加載上去。到時(shí)它們才擁有共同的父Viewself.LoginWaytableView。