Sti*_*ing 3 uibutton ios swift
我正在尝试创建一个图像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)
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过: 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
以上都不起作用:(
任何帮助/建议/建议非常感谢!
And*_*aya 11
当我尝试你的代码时,它崩溃了.问题是你在初始化视图之前尝试添加约束,添加约束应该在viewWillLayoutSubviews()中
在任何情况下,我建议创建更简单的按钮,即使按钮居中视图
let btn = UIButton(frame: CGRect(x:0 , y:0, width:100, heigth: 60))
btn.center = self.view.center
self.view.addSubview(btn)
Run Code Online (Sandbox Code Playgroud)
以上将自动将按钮限制在视图的中心
希望能帮助到你!
| 归档时间: |
|
| 查看次数: |
13492 次 |
| 最近记录: |