Swift 3: You can create a UIButton
programmatically
either inside a methods scope for example in ViewDidLoad()
Be sure to add constraints to the button, otherwise you wont see it
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.target(forAction: #selector(buttonAction), withSender: self)
//button.backgroundColor etc
view.addSubview(button)
@objc func buttonAction() {
//some Action
}
or outside your scope as global variable to access it from anywhere in your module
let button: UIButton = {
let b = UIButton()
b.translatesAutoresizingMaskIntoConstraints = false
//b.backgroundColor etc
return b
}()
and then you setup the constraints
func setupButtonView() {
view.addSubview(button)
button.widthAnchor.constraint(equalToConstant: 40).isActive = true
button.heightAnchor.constraint(equalToConstant: 40).isActive = true
// etc
}