Masonry报错AutoLayout的条件

尝试在项目中用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;
}

结果报错如下:

 *** 
 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:

崩溃原因大致意思是说,这个UIView和UITableView没有一个共同的父View。
得出使用自动布局autoLayout(Masonry基于约束autoLayout)需要两个View拥有一个共同的父View。很明显,headerView 和 self.LoginWayTableView两个View在目前这个tableView的代理函数中还没有共同的父View。因为headerView还没有加载在self.LoginWayTableView上面。只有当此函数执行结束的时候才被加载上去。到时它们才拥有共同的父Viewself.LoginWaytableView。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容