couldn't find a common superview

console报错信息

couldn’t find a common superview for <UIScrollView: 0x7fb8a401ac00; frame = (0 0; 0 0); clipsToBounds = YES; gestureRecognizers = ; layer = ; contentOffset: {0, 0}; contentSize: {0, 0}> and <UIView: 0x7fb8a3c1c970; frame = (0 0; 375 667); autoresize = W+H; layer = >


大致原因

不能为scrollView找到父视图, 原因为当scrollView被创建后, 使用masonry对scrollView进行设置约束时会找视图进行参考, 我们这里是以其父视图view进行参考, 但此时scrollView并未添加到view中, 所以运行会直接崩掉

解决办法

修改添加到父控件的代码的执行顺序即可

原代码:

1
2
3
4
5
6
7
UIScrollView *scrollView = UIScrollView.new;   
scrollView.backgroundColor = [UIColor brownColor];   
[scrollView mas_makeConstraints:^(MASConstraintMaker *make)
{
       make.size.mas_equalTo(self.view);   
}];
[self.view addSubview:scrollView];

改正后:

1
2
3
4
5
6
7
UIScrollView *scrollView = UIScrollView.new;
[self.view addSubview:scrollView]; //放到这里
scrollView.backgroundColor = [UIColor brownColor];   
[scrollView mas_makeConstraints:^(MASConstraintMaker *make)
{
      make.size.mas_equalTo(self.view);
}];
0%