通常来说,约束的类型应该都是 NSLayoutConstraint,可是从 Xcode 4 开始,增长了 Auto Layout 功能时,考虑到当开发者在 IB 中建立 View 后,没有显示的主动添加任何约束,会致使视图没法显示,所以 IB 会根据你拖动 View 的位置,自动的帮你加上约束,避免视图没法显示,由于这种约束是 IB 自动添加的,所以类名叫 NSIBPrototypingLayoutConstraint,而且这种约束没法经过 NSLog(@"%@", self.constraints);
打印出来。bash
通常来说,这种状况下,对当前 View 设置ide
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.ui
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.this
简单翻译一下,意思是说: 使用代码建立 View 时,这个属性默认是 YES,而后你就能够经过设置其 frame、bounds、center 等属性,自动的转换为 autoLayout 的约束。保证视图约束的完整性,可以很好的显示。spa
可是,你一旦这么作了,那么就不能额外给这个 View 添加约束了。由于,这个 View 已经有了 transfer 过来的约束,你再添加的话,约束将会冲突。翻译
若是你但愿可以手动地添加约束,来知足需求,那么就须要设置 translatesAutoresizingMaskIntoConstraints = NO
。code
在使用 IB 时,这个属性默认是 NO。
一点疑惑 官方的说法中,在 IB 中,这个属性应该是 NO,可是我经过 xib 建立的 UITableViewCell ,在
awakeFromNib
方法中,打印出该属性是 YES。 就是由于这样,才致使我在awakeFromNib
方法中使用 masonry 添加的约束有了冲突。
在 IB 中,显示的为 view 添加一些约束,而后所有选择这些约束,在 File Inspector
中,勾选 Remove at build time
;

问题的根本是 IB 自动建立了咱们不想要的约束,IB 自动建立的缘由是 view 上没有约束,所以咱们随意给 view 添加一些无用的约束,而后让其在 building 时删除掉。 这样子,当代码执行到 masonry make 建立约束时,这个 view 将是一个干净的 view。
这个属性呢,其实原本的使用场景是这样: 在开发过程当中,有时候须要预览一些布局,那么在 Storyboard 上添加约束,就会很方便,这样子在不执行代码的状况下,就可以测试验证咱们的约束是否正确。
可是呢,在实际开发中,极可能你们以为在 storyboard 上添加约束比较麻烦,团队之间协做很差,所以但愿可以使用代码建立约束,好比 masonry 这种工具。
很简单,只须要在运行时,将 storyboard 中添加的约束所有删除掉。这样子,storyboard 中添加的约束不会对代码添加的约束形成任何影响。另外一方面,在 storyboard 中布局能够更加方便,且 storyboard 中不会出现一堆关于约束的 warning。
有什么问题,能够留言,我会尽快回复~