ludluck ludluck - 1 year ago 56
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() {
// Do any additional setup after loading the view, typically from a nib.


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

func createButtons() {
for index in 0...4 {
buttons[index].setBackgroundImage(manImage, forState: .Normal)
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download