Search code examples
iosuibuttonswift3nslayoutconstraint

UIButtons not sticking to UIView edges


Hi and thanks in advance. I'm attempting to bind two UIButtons to a UIViewController's view like so:

First by declaring them:

fileprivate var deleteButton: UIButton = UIButton(type: .system)
fileprivate var addButton: UIButton = UIButton(type: .system)

Next in setting them up:

private func setupButtons() {

    deleteButton.setTitle("Delete", for: .normal)
    addButton.setTitle("Add", for: .normal)

    deleteButton.sizeToFit()
    addButton.sizeToFit()

    deleteButton.alpha = 1
    addButton.alpha = 1

    view.addSubview(deleteButton)
    view.addSubview(addButton)

    view.addConstraint(NSLayoutConstraint(item: deleteButton,
                                          attribute: .leading,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .leading,
                                          multiplier: 1.0,
                                          constant: 0))

    view.addConstraint(NSLayoutConstraint(item: deleteButton,
                                          attribute: .bottom,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .bottom,
                                          multiplier: 1.0,
                                          constant: 0))

    view.addConstraint(NSLayoutConstraint(item: addButton,
                                          attribute: .trailing,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .trailing,
                                          multiplier: 1.0,
                                          constant: 0))

    view.addConstraint(NSLayoutConstraint(item: addButton,
                                          attribute: .bottom,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .bottom,
                                          multiplier: 1.0,
                                          constant: 0))

}

But running the simulator sticks the two UIButtons in the top left, the default CGRect frames assigned to them both.

Might you know what i'm doing wrong? I feel like i'm close but perhaps it has something to do with re-drawing the view?

Halp!


Solution

  • You should set translatesAutoresizingMaskIntoConstraints to false

    // before activate constraint
    
    deleteButton.translatesAutoresizingMaskIntoConstraints = false
    addButton.translatesAutoresizingMaskIntoConstraints = false
    

    Also, you have to set isActive = true instead of using addConstraint method