同时使用 IB 和 Masonry 时,如何删除 NSIBPrototypingLayoutConstraint

732 阅读3分钟

为什么出现一种约束叫做 NSIBPrototypingLayoutConstraint

一般来讲,约束的类型应该都是 NSLayoutConstraint,但是从 Xcode 4 开始,增加了 Auto Layout 功能时,考虑到当开发者在 IB 中创建 View 后,没有显示的主动添加任何约束,会导致视图无法显示,因此 IB 会根据你拖动 View 的位置,自动的帮你加上约束,避免视图无法显示,因为这种约束是 IB 自动添加的,因此类名叫 NSIBPrototypingLayoutConstraint,并且这种约束无法通过 NSLog(@"%@", self.constraints); 打印出来。

深层次的原因

一般来讲,这种情况下,对当前 View 设置

view.translatesAutoresizingMaskIntoConstraints = NO;

即可。

对于 translatesAutoresizingMaskIntoConstraints 属性,官方文档时这样写的:

Discussion If this property’s value is YES, the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask. This also lets you modify the view’s size and location using the view’s frame, bounds, or center properties, allowing you to create a static, frame-based layout within Auto Layout.

Note that the autoresizing mask constraints fully specify the view’s size and position; therefore, you cannot add additional constraints to modify this size or position without introducing conflicts. If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to NO, and then provide a nonambiguous, nonconflicting set of constraints for the view.

By default, the property is set to YES for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to NO.

简单翻译一下,意思是说: 使用代码创建 View 时,这个属性默认是 YES,然后你就可以通过设置其 frame、bounds、center 等属性,自动的转换为 autoLayout 的约束。保证视图约束的完整性,能够很好的显示。

但是,你一旦这么做了,那么就不能额外给这个 View 添加约束了。因为,这个 View 已经有了 transfer 过来的约束,你再添加的话,约束将会冲突。

如果你希望能够手动地添加约束,来满足需求,那么就需要设置 translatesAutoresizingMaskIntoConstraints = NO

在使用 IB 时,这个属性默认是 NO。

一点疑惑 官方的说法中,在 IB 中,这个属性应该是 NO,但是我通过 xib 创建的 UITableViewCell ,在 awakeFromNib 方法中,打印出该属性是 YES。 就是因为这样,才导致我在 awakeFromNib 方法中使用 masonry 添加的约束有了冲突。

解决问题的最终办法

在 IB 中,显示的为 view 添加一些约束,然后全部选择这些约束,在 File Inspector 中,勾选 Remove at build time;



example-1.png

为什么上述方法可以解决问题

问题的根本是 IB 自动创建了我们不想要的约束,IB 自动创建的原因是 view 上没有约束,因此我们随意给 view 添加一些无用的约束,然后让其在 building 时删除掉。 这样子,当代码执行到 masonry make 创建约束时,这个 view 将是一个干净的 view。

Placeholder : Remove At build time

这个属性呢,其实本来的使用场景是这样: 在开发过程中,有时候需要预览一些布局,那么在 Storyboard 上添加约束,就会很方便,这样子在不执行代码的情况下,就能够测试验证我们的约束是否正确。

但是呢,在实际开发中,很可能大家觉得在 storyboard 上添加约束比较麻烦,团队之间协作不好,因此希望能够使用代码创建约束,比如 masonry 这种工具。

很简单,只需要在运行时,将 storyboard 中添加的约束全部删除掉。这样子,storyboard 中添加的约束不会对代码添加的约束造成任何影响。另一方面,在 storyboard 中布局可以更加方便,且 storyboard 中不会出现一堆关于约束的 warning。

后记

有什么问题,可以留言,我会尽快回复~