我试图通过编程方式创建一个图片UIButton并设置其位置,而不是使用Interface Builder。原因是我将根据ViewController中的某些逻辑显示/隐藏该按钮。然而,我已经花了过去大约4个小时搜索,但一无所获。我尝试了以下方法:
- 约束:似乎是推荐的方法
- 将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
上述方法都无效 :(
非常感谢您的任何帮助/建议/意见!