Dan Saps Dan Saps - 1 year ago 106
Swift Question

Set the center of a uibutton programmatically - SWIFT

I have a

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

Answer Source

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

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