利用约束优先级解决Autolayout冲突
问题发生
当你在运行程序的时候,发现Xcode的终端打印了一些控件的布局冲突信息时,类似于如下:
代码语言:javascript复制2018-06-26 15:13:08.067547 xxxx[302:38207] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
...
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
这就说明你当前的自动布局存在一些问题。
问题解决
当遇到布局问题时,我们可以在Xcode中断点调试栏添加一个Symbolic Breakpoint symbol:UIViewAlertForUnsatisfiableConstraints
断点调试
断点信息填写
如上添加完成后重新运行程序到打印布局错误log的地方,断点将会发生作用,然后按照以下步骤运行,终端会给出有问题的布局约束,接下来我们修改此约束的优先级就可以了。
image
log
我上面的布局错误提示是:nameBtn水平布局约束有问题。注意看前面的H是水平布局,V是垂直布局。我使用的是purelayout布局框架,只要block里面是nameBtn的水平约束就行。
代码语言:javascript复制NSLayoutConstraint.autoSetPriority(900) {
[weak self] in
self?.nameBtn.autoPinEdge(toSuperviewEdge: .trailing, withInset: 15)
}
至此我的问题已解决,终端不再打印约束错误。