Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 511
thedansaps Avatar asked Aug 26 '15 06:08

thedansaps


2 Answers

Try .center property like

myButton.center = self.view.center

You can also specify x and y If you need.

myButton.center.x = self.view.center.x // for horizontal
myButton.center.y = self.view.center.y // for vertical
like image 61
iRiziya Avatar answered Oct 22 '22 19:10

iRiziya


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()
like image 36
Prabhu.Somasundaram Avatar answered Oct 22 '22 18:10

Prabhu.Somasundaram