ios - NSLayoutConstraint 不适用于 uibutton 和 uilabel

标签 ios swift nslayoutconstraint

我创建一个 uiable 和 uibutton

@IBOutlet weak var label_one: UILabel!
@IBOutlet weak var btn_one: UIButton!

并设置以下尾随和前导约束

        self.btn_one.translatesAutoresizingMaskIntoConstraints=false
    let contariants=NSLayoutConstraint(item:self.view,attribute:NSLayoutAttribute.LeadingMargin , relatedBy: NSLayoutRelation.Equal, toItem: btn_one, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1.0, constant: 20)
    let trailingConstraints=NSLayoutConstraint(item: self.view, attribute:NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: btn_one, attribute:NSLayoutAttribute.Trailing , multiplier: 1.0, constant:20 )

    self.view.addConstraint(contariants)
    self.view.addConstraint(trailingConstraints)

//但它根本不起作用并给出以下警告 可能至少以下列表中的约束之一是您不想要的。 尝试这个: (1) 查看每个约束并尝试找出您不期望的约束; (2) 找到添加了不需要的约束的代码并修复它。 ( "", “UIButton:0x7ff8c84b0b60'按钮'(名称:'|':UIView:0x7ff8c85226d0)>” )

将尝试通过打破约束来恢复

在 UIViewAlertForUnsatisfiableConstraints 处创建一个符号断点以在调试器中捕获此情况。 中列出的 UIView 上的 UIConstraintBasedLayoutDebugging 类别中的方法也可能会有所帮助。 2015-12-16 10:39:01.918 ConstraintsExample[2635:38168] 无法同时满足约束。 可能至少以下列表中的约束之一是您不想要的。 尝试这个: (1) 查看每个约束并尝试找出您不期望的约束; (2) 找到添加了不需要的约束的代码并修复它。 ( "", "UIButton:0x7ff8c84b0b60'按钮'(名称:'|':UIView:0x7ff8c85226d0 )>", "", ”” )

将尝试通过打破约束来恢复

在 UIViewAlertForUnsatisfiableConstraints 处创建一个符号断点以在调试器中捕获此情况。 中列出的 UIView 上的 UIConstraintBasedLayoutDebugging 类别中的方法也可能会有所帮助。

最佳答案

此错误是因为您试图使 View 同时执行多个约束。当您从 IB 中将元素拖放到 View 上时,它会对给定位置产生基本约束。 当您尝试以下“addConstraint”方法时,编译器无法理解要遵循哪个约束。

如果您以编程方式制作按钮和标签,则上述内容将起作用。 PFB 的一篇文章讨论了这个问题:

Programmatically Add CenterX/CenterY Constraints

如果您想修改 Storyboard 上的现有约束: 在元素上添加约束: adding an element contraint

不要使用该约束作为与代码的连接: make the constraint part of the code

关于ios - NSLayoutConstraint 不适用于 uibutton 和 uilabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34304932/

相关文章:

ios 5.0 在 ios 模拟器问题中登录到 twitter

ios - 将 ipa 文件上传到应用商店连接时卡住了

ios - TableView 单元格的 subview 的框架更改不会发生,直到 View 出现

swift - 更改键盘动画弹跳的 Storyboard约束

ios - NSPredicate for NSString中的问题

ios - 快速关闭不能覆盖任何

ios - 使用完成 block 连续显示两个 UIAlertController 对象

swift - 给 UISegmentedControl 添加 NSLayoutConstraints 导致 UISegmentedControl 消失

ios - 在 tableHeaderView 中使用自动布局

ios - 我看不到这个 NSLayoutConstraints 的错误