Set the center of a UIButton programmatically - SW

2019-04-24 10:38发布

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?

4条回答
Anthone
2楼-- · 2019-04-24 10:58

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
查看更多
疯言疯语
3楼-- · 2019-04-24 11:03

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()
查看更多
Summer. ? 凉城
4楼-- · 2019-04-24 11:14

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.

查看更多
我想做一个坏孩纸
5楼-- · 2019-04-24 11:17

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.

查看更多
登录 后发表回答