我正在尝试创建一个图像UIButton并使用接口生成器以编程方式设置其位置。原因是我会显示/隐藏基于ViewController中的一些逻辑的按钮。但是,我花了过去〜4小时寻找无济于事。我曾尝试以下方法:swift 3:如何在UIView上居中对齐(垂直和水平)UIButton?
- 约束:貌似推荐的方法
- 设置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