简体   繁体   中英

How to change position of UIButton?

Nothing happens but why ???

@IBOutlet weak var button10: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    button10.center = CGPoint(x: self.view.frame.x/2, y: self.view.frame.y/2)

 }

Add constraints for center in view

var constX = NSLayoutConstraint(item: button10, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
view.addConstraint(constX)

var constY = NSLayoutConstraint(item: button10, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
view.addConstraint(constY)

As Ashhish said, add two constraints between the parent view and the button. But this can also be done using the awesome Github project Cartography :

layout(view, button) {
    parent, button in
    button.centerX == parent.centerX
    button.centerY == parent.centerY
}

Very neat!

You can include Cartography using Cocoapods .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM