[英]How can we provide horizontal spacing between buttons using auto-layouts(constraint with visual formate)
[英]How do I programmatically put constraint to buttons (horizontal spacing)
我想并排放置两个按钮。
一个( testButton
)当前位于正确的位置- 垂直和水平对齐 -使用Interface Builder自动布局。
我们看看吧 :
我想以编程方式并排放置另一个( okButton
):
我想要的预览:
我添加了一个CenterY约束和一个Leading / Trailing约束,但是它不起作用,测试按钮的UIButton宽度会增加。
让我们看一下Debug View Hierarchy
:
和我的代码:
override func viewDidLoad() {
super.viewDidLoad()
let constraintAlignY = NSLayoutConstraint(
item: okButton,
attribute: .CenterY,
relatedBy: .Equal,
toItem: testButton,
attribute: .CenterY,
multiplier: 1,
constant: 0)
let constraintXSpace = NSLayoutConstraint(
item: okButton,
attribute: .Leading,
relatedBy: .Equal,
toItem: testButton,
attribute: .Trailing,
multiplier: 1,
constant: 8)
view.addConstraint(constraintAlignY)
view.addConstraint(constraintXSpace)
}
警告控制台:
2015-05-09 23:03:10.439 MainThreading[10227:663061] 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. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x7b8c8ee0 UIButton:0x7b8cde90'test'.centerY == UIView:0x7b8ced40.centerY>",
"<NSIBPrototypingLayoutConstraint:0x7b8c40f0 'IB auto generated at build time for view with fixed frame' V:|-(191)-[UIButton:0x7b8ce8d0'ok'] (Names: '|':UIView:0x7b8ced40 )>",
"<NSIBPrototypingLayoutConstraint:0x7b8c77f0 'IB auto generated at build time for view with fixed frame' V:[UIButton:0x7b8ce8d0'ok'(30)]>",
"<NSLayoutConstraint:0x7b8c4f50 UIButton:0x7b8ce8d0'ok'.centerY == UIButton:0x7b8cde90'test'.centerY>",
"<NSLayoutConstraint:0x7b8da380 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7b8ced40(480)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7b8c4f50 UIButton:0x7b8ce8d0'ok'.centerY == UIButton:0x7b8cde90'test'.centerY>
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.
(lldb)
任何想法 ? 谢谢 !
如果您添加视图并且自己不添加任何约束,则系统会为您添加约束(在顶部和左侧),所以我认为这就是问题所在。
这些系统添加的约束与您在代码中添加的约束冲突。 由于您的最终目标是动态添加视图,因此应在代码中而不是IB中添加“确定”按钮。 对于任何添加了代码的视图,请确保将translatesAutoresizingMaskIntoConstraints
设置为false
。
如果您确实需要在IB中添加该按钮,则可以通过选择“ 在构建时删除 ”复选框来为其赋予约束,但可以将其删除。 然后,在代码中添加新代码将是安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.