0

I am trying to programmatically add a button view object to my scene for an iOS app written in swift. I am trying to follow the answer here https://stackoverflow.com/a/36263784

But I cannot see the button on the scene. I call this method from my viewDidLoad method.

    func buildLoginButton() -> UIButton
{
    let button = UIButton()
    button.backgroundColor = .greenColor()
    button.setTitle("Test Button", forState: .Normal)
    self.view.addSubview(button)

    let c1 = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)

    let c2 = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)

    button.widthAnchor.constraintEqualToAnchor(nil, constant: 200).active = true
    button.heightAnchor.constraintEqualToAnchor(nil, constant: 100).active = true

     NSLayoutConstraint.activateConstraints([c1, c2])
    view.bringSubviewToFront(button)

    return button
}
Community
  • 1
  • 1
capturesteve
  • 373
  • 2
  • 10

1 Answers1

1
let button = UIButton()
self.view.addSubview(button)

Stop! You forgot to say this:

button.translatesAutoresizingMaskIntoConstraints = false`

You must say this on any view that you create, put into the interface, and try to apply constraints to.

matt
  • 515,959
  • 87
  • 875
  • 1,141