2017-02-18 1150 views
2

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

  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

无上述作品:(

任何帮助/咨询/建议非常感谢!

+0

你应该在设置约束之前将按钮添加到超级视图。这应该是它不工作的原因 – KrishnaCA

回答

6

当我试过你的代码时,它崩溃了。问题是你试图视图初始化之前添加约束,增加约束应该是内部viewWillLayoutSubviews()

在任何情况下 我建议创建按钮简单,即 为了使按钮为中心的视图

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

以上会自动约束的按钮来查看

希望它能帮助中心!

+0

我的上面的片段被添加到viewDidLoad() –

+0

谢谢@AndreeWijaya!在'viewWillLayoutSubviews()'函数内部添加我的约束就有诀窍了! –