I'm trying to create an image UIButton and set its position programmatically vs using Interface Builder. The reason being I'll be showing/hiding the button based on some logic in ViewController. However, i've spent the past ~4hrs searching to no avail. I have tried following approaches:
CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
Here's the full code:
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)
}
}
I've also tried doing: playButton.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
as well as:
playButton.center.x = self.view.center.x
playButton.center.y = self.view.center.y
None of the above works :(
Any help/advice/suggestions are much appreciated!
When I tried your code, it crashed. The problem was you were trying to add constraints before the view is initialized, adding constraints should be inside viewWillLayoutSubviews()
In any case I would suggest to create the button simpler, i.e. To make the button centering the view
let btn = UIButton(frame: CGRect(x:0 , y:0, width:100, heigth: 60))
btn.center = self.view.center
self.view.addSubview(btn)
The above will automatically constraints the button to the center of the view
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With