Swift 3:如何在UIView上垂直居中和水平居中对齐UIButton?

6
我试图通过编程方式创建一个图片UIButton并设置其位置,而不是使用Interface Builder。原因是我将根据ViewController中的某些逻辑显示/隐藏该按钮。然而,我已经花了过去大约4个小时搜索,但一无所获。我尝试了以下方法:
  1. 约束:似乎是推荐的方法
  2. 将UIButton.center属性设置为CGPoint(x:self.view.frame.width / 2,y:self.view.frame.height / 2)
这是完整的代码:
    class ViewController: UIViewController{
    //this is here so i can access playButton across different functions that i'll define in this ViewController
    let playButton:UIButton = {
      let play_btn = UIButton()
        play_btn.setImage(UIImage(named:"my_button_image.png"), for: UIControlState.normal)
        play_btn.translatesAutoresizingMaskIntoConstraints = false
        return play_btn
    }()

    override func viewDidLoad() {

       super.viewDidLoad()


       playButton.addTarget(self, action:#selector(self.toggle), for: .touchDown)
       let centerX = NSLayoutConstraint(item: self.playButton, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
       let centerY = NSLayoutConstraint(item: self.playButton, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)

       self.view.addConstraints([centerX, centerY])

       view.addSubview(playButton)

    }
}

我也尝试了以下方法:

playButton.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)

以及:

playButton.center.x = self.view.center.x playButton.center.y = self.view.center.y

上述方法都无效 :(

非常感谢您的任何帮助/建议/意见!


在设置约束之前,您应该将按钮添加到父视图中。这可能是它无法正常工作的原因。 - KrishnaCA
1个回答

20

我尝试了你的代码,但它崩溃了。问题在于你尝试在视图初始化之前添加约束,应该将添加约束的过程放在viewWillLayoutSubviews()方法中。

无论如何,我建议简化创建按钮的过程,例如让按钮居中于视图中央。

let btn = UIButton(frame: CGRect(x:0 , y:0, width:100, heigth: 60))
btn.center = self.view.center
self.view.addSubview(btn)

上述操作将自动将按钮限制在视图中心

希望能帮到您!


我的上述代码片段被添加到了viewDidLoad()函数中。 - Andree Wijaya
谢谢@AndreeWijaya!将我的限制条件添加到viewWillLayoutSubviews()函数中就解决了问题! - Still Questioning

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接