Background
I’m trying to create a UIButton with a 300px width and 200px height.
Then, I’m trying to position that UIButton centred horizontally and 50 pixels from the bottom.
When running the code in the iOS simulator, the result is unexpected, the button height and width is not correct, the UIButton appears cropped. Image below.
Question
What corrections to the code below must be made so that the UIButton layout is positioned correctly and retains the correct sized UIButton frame?
Code
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
addButton1()
}
func addButton1() {
let myButton1 = UIButton(type: UIButton.ButtonType.custom)
myButton1.frame.size = CGSize(width: 300, height: 200)
myButton1.setTitle("Hello", for:UIControl.State())
myButton1.backgroundColor = .blue
view.addSubview(myButton1)
myButton1.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myButton1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
myButton1.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50)
])
}
}
Image
You are mixing legacy frame approach with AutoLayout and that would not work. I suggest to stick with AutoLayout and so your code could be:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
addButton1()
}
func addButton1() {
let myButton1 = UIButton(type: UIButton.ButtonType.custom)
myButton1.setTitle("Hello", for:UIControl.State())
myButton1.backgroundColor = .blue
view.addSubview(myButton1)
myButton1.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myButton1.widthAnchor.constraint(equalToConstant: 300),
myButton1.heightAnchor.constraint(equalToConstant: 200),
myButton1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
myButton1.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50)
])
}
}