Используйте этот код:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(button)
setupConstraints()
}
lazy var button: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Button", for: .normal)
button.backgroundColor = .blue
//your action here
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
return button
}()
private func setupConstraints() {
button.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 100)
let left = NSLayoutConstraint(item: button, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 50)
let right = NSLayoutConstraint(item: button, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: -50)
let height = NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)
view.addConstraints([top, left, right, height])
}
@objc func buttonAction() {
print("Button has pressed")
}
}