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?
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With