如何为约束获取随机 CGFloat?

How to get a random CGFloat for a constraint?

我正在尝试随机化 swift 中按钮的前导约束。要激活它,我 select 按下一个按钮。当我第一次 select 按钮时,它运行良好,但此后的所有时间,它都会在 NSLog 中显示很多错误。这是代码:

let button = UIButton()
@IBAction func start(sender: UIButton) {
     let randomNumber = Int(arc4random_uniform(180) + 30)
     let cgfloatrandom = CGFloat(randomNumber)
     button.hidden = false
     button.translatesAutoresizingMaskIntoConstraints = false
     NSLayoutConstraint.activateConstraints([
        button.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: cgfloatrandom),
        button.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 390),
        button.widthAnchor.constraintEqualToConstant(75),
        button.heightAnchor.constraintEqualToConstant(75)
        ])
}

请帮忙。谢谢你。安东

问题是您要向已经正确约束的按钮添加约束。虽然您可以删除所有约束并重新创建它们,但这确实效率低下,不推荐这样做。

我建议只保留对前导约束的引用,这将允许您在每次点击按钮修改 constant.

时访问它

为此,请为您的前导约束实现一个 属性,如下所示:

var leadingConstraint: NSLayoutConstraint!

创建此按钮时,您还需要对其进行适当的约束。您将在此处创建特殊的前导约束。这是在按钮操作功能之外完成的,可能在 viewDidLoad:

button = UIButton() 
button.translatesAutoresizingMaskIntoConstraints = false
//...

leadingConstraint = button.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: 0)

NSLayoutConstraint.activateConstraints([
    leadingConstraint,
    button.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 390),
    button.widthAnchor.constraintEqualToConstant(75),
    button.heightAnchor.constraintEqualToConstant(75)
])

现在当按钮被点击时,你不需要设置translatesAutoresizingMaskIntoConstraints,你可以简单地更新现有前导约束的constant

@IBAction func start(sender: UIButton) {
     button.hidden = false

     let randomNumber = Int(arc4random_uniform(180) + 30)
     leadingConstraint.constant = CGFloat(randomNumber)
}