ludluck ludluck - 2 months ago 7
Swift Question

Why does this object creation loop produce simultaneous constraint errors?

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))
}
}
}


I get
Unable to simultaneously satisfy constraints.
errors. Why does this happen, and are there any suggestions to fix this?

Thank you.

I don't know what else to say, but Stack is asking for more text.

Answer

Your buttons array contains four references to a single instance of UIButton. Try this instead:

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

Also, you probably need to set translatesAutoresizingMaskIntoConstraints = false on each button.