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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
回答2:
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()
回答3:
I should be
yourButton.setCenter(self.view.center);
But keep in mind that if you programmatically set the frame of a view, your layout constraints might not work as intended.
回答4:
since you are using constraints, you won't be able to set the center so you need to use constraints to set the center as well:
let centerYCon = NSLayoutConstraint(item: labelMessage,
attribute: .CenterY,
relatedBy: .Equal,
toItem: contentView,
attribute: .CenterY,
multiplier: 1.0,
constant: 0.0);
contentView.addConstraint(centerYCon);
let centerXCon = NSLayoutConstraint(item: labelMessage,
attribute: .CenterX,
relatedBy: .Equal,
toItem: contentView,
attribute: .CenterX,
multiplier: 1.0,
constant: 0.0);
contentView.addConstraint(centerXCon);
I'm assuming that you know what "programmatically" means with autolayout constraints. If you are truly using autolayout then you must have set the properties of your button to setTranslatesAutoresizingMaskIntoConstraints to false.