0

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
   }
}

enter image description here

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?

ergl1s
  • 1
  • 1
  • "everything works well" So what's the problem? – matt Oct 29 '21 at 14:33
  • @matt The problem is that I think this is a very bad solution because it makes me set any contentEdgeInsets except zero. Do you see "-0.000001"? – ergl1s Oct 29 '21 at 18:16

1 Answers1

0

may be try this

button.contentHorizontalAlignment = .center