I need to attach title of UIButton to the top-right corner, but when I use .contentVerticalAlignment property, there is a space between the top and the title.
class ViewController: UIViewController {
let button: UIButton = {
let button = UIButton()
button.setTitle("1250 km", for: .normal)
button.setTitleColor(.black, for: .normal)
button.backgroundColor = .green
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(button)
NSLayoutConstraint.activate([
button.widthAnchor.constraint(equalToConstant: 150),
button.heightAnchor.constraint(equalToConstant: 100),
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
// button.contentEdgeInsets = UIEdgeInsets(top: 0, left: -0.000001, bottom: 0, right: 0)
button.contentVerticalAlignment = .top
button.contentHorizontalAlignment = .right
}
}
But when I uncomment this line, everything works well and there is no space between top and title. (Pay attention to the 'left' value)
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: -0.000001, bottom: 0, right: 0)
Can anyone tell me a better solution?