gpt4 book ai didi

ios - swift 3 : How to center align (vertically & horizontally) UIButton on UIView?

转载 作者:可可西里 更新时间:2023-10-31 23:56:19 26 4
gpt4 key购买 nike

我正在尝试创建一个图像 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

以上都不行:(

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

最佳答案

当我尝试你的代码时,它崩溃了。问题是您试图在 View 初始化之前添加约束,添加约束应该在 viewWillLayoutSubviews() 中

无论如何我建议创建更简单的按钮,即使按钮居中 View

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

上面会自动将按钮约束到 View 的中心

希望对您有所帮助!

关于ios - swift 3 : How to center align (vertically & horizontally) UIButton on UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42310766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com