为什么此对象创建循环会产生同时约束错误?

时间:2016-09-30 16:31:42

标签: ios swift constraints

class ViewController: UIViewController {

    let manImage = UIImage(named: "man.png")

    var buttons = Array(count: 5, repeatedValue: UIButton())

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        createButtons()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func createButtons() {
        for index in 0...4 {
            buttons[index].setBackgroundImage(manImage, forState: .Normal)
            self.view.addSubview(buttons[index])
            self.view.addConstraint(NSLayoutConstraint(
                item: buttons[index],
                attribute: .CenterX,
                relatedBy: .Equal,
                toItem: view,
                attribute: .CenterX,
                multiplier: 1,
                constant: 0))
        }
    }
}

我收到Unable to simultaneously satisfy constraints.错误。为什么会发生这种情况,有什么建议可以解决这个问题吗?

谢谢。

我不知道还有什么可说的,但是Stack要求更多的文字。

1 个答案:

答案 0 :(得分:1)

您的buttons数组包含对UIButton的单个实例的四个引用。试试这个:

let buttons = (0..<4).map({_ in UIButton()})

此外,您可能需要在每个按钮上设置translatesAutoresizingMaskIntoConstraints = false