在使用Masonry布局,获取控件的frame值的时候,获取的frame都是frame = (0 0; 0 0);
查阅资料发现解决问题的方法,以此记录:
代码:
__eWeak(weak);
UILabel *label = [UILabel labelWithTitle:@"1231231" color:[UIColor redColor] fontSize:14.f alignment:NSTextAlignmentLeft];
[self.view addSubview:label];
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(weak.view.mas_top).offset(100);
make.left.equalTo(weak.view.mas_left).offset(30);
make.right.equalTo(weak.view.mas_right).offset(-30);
make.height.mas_equalTo(20);
}];
NSLog(@"%@",label);
打印结果:
UILabel: 0x7fe98df5e150; frame = (0 0; 0 0); text = '1231231'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x608000289c90>
解决办法一:
修改代码:
__eWeak(weak);
UILabel *label = [UILabel labelWithTitle:@"1231231" color:[UIColor redColor] fontSize:14.f alignment:NSTextAlignmentLeft];
[self.view addSubview:label];
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(weak.view.mas_top).offset(100);
make.left.equalTo(weak.view.mas_left).offset(30);
make.right.equalTo(weak.view.mas_right).offset(-30);
make.height.mas_equalTo(20);
}];
[self.view layoutIfNeeded];
NSLog(@"%@",label);
打印结果:
UILabel: 0x7ff6f5b394e0; frame = (30 100; 354 20); text = '1231231'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60400009df60>
解决办法二:
修改代码:
__eWeak(weak);
UILabel *label = [UILabel labelWithTitle:@"1231231" color:[UIColor redColor] fontSize:14.f alignment:NSTextAlignmentLeft];
[self.view addSubview:label];
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(weak.view.mas_top).offset(100);
make.left.equalTo(weak.view.mas_left).offset(30);
make.right.equalTo(weak.view.mas_right).offset(-30);
make.height.mas_equalTo(20);
}];
//延迟1秒获取
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@",label);
});
打印结果:
UILabel: 0x7fec99a44c00; frame = (30 100; 354 20); text = '1231231'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x604000292bb0>
总结:
Autolayout最终也是转成frame,masonry是建立在autolayout之上的。Autolayout是在block中实现的,并不是即时转成frame值的,所以在获取的时候需要延迟一秒或者调用官方layoutIfNeeded方法。 延迟1秒不用说,layoutIfNeeded是立即布局的(官方提供的方法,可以去看官方api说明)。
参考:Cocoa开发者社区-无夜之星辰 ,非常感谢。mp.weixin.qq.com/s/QKEJEblH1RN9jGtVDi_d9A