Dan Saps Dan Saps - 4 months ago 21
Swift Question

Set the center of a uibutton programmatically - SWIFT

I have a

UIButton
inside a
UIView
, my
UIButton
has constraints which I set in storyboard. Now, I want to set the center of the
UIButton
at the center of the
UIView
. How will I do that programmatically?

Answer

This approach is using Using NSLayoutConstraint where self.cenBut is the IBoutlet for your button.

func setupConstraints() {
    let centerX = NSLayoutConstraint(item: self.cenBut, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
    let centerY = NSLayoutConstraint(item: self.cenBut, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
    let height = NSLayoutConstraint(item: self.cenBut, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 22)
    self.cenBut.translatesAutoresizingMaskIntoConstraints = false
    self.view.addConstraints([centerX, centerY, height])
}

In viewDidLoad()

self.view.removeConstraints(self.view.constraints)
self.setupConstraints()