我正在尝试创建一个图像UIButton,并使用Interface Builder以编程方式设置其位置。原因是我将根据ViewController中的一些逻辑显示/隐藏按钮。然而,我花了过去~4小时搜索无济于事。我尝试了以下方法:
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
以上都不起作用:(
非常感谢任何帮助/建议/建议!
答案 0 :(得分:11)
当我尝试你的代码时,它崩溃了。问题是你在初始化视图之前尝试添加约束,添加约束应该在viewWillLayoutSubviews()
中无论如何 我建议创建更简单的按钮,即 使按钮居中于视图
let btn = UIButton(frame: CGRect(x:0 , y:0, width:100, heigth: 60))
btn.center = self.view.center
self.view.addSubview(btn)
上面会自动将按钮限制在视图的中心
希望它有所帮助!