首页 > 解决方案 > Swift UIButton .contentVerticalAlignment 属性不起作用

问题描述

我需要将 UIButton 的标题附加到右上角,但是当我使用 .contentVerticalAlignment 属性时,顶部和标题之间有一个空格。

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

在此处输入图像描述

但是当我取消注释这一行时,一切正常,顶部和标题之间没有空格。(注意“左”值)

button.contentEdgeInsets = UIEdgeInsets(top: 0, left: -0.000001, bottom: 0, right: 0)

谁能告诉我更好的解决方案?

标签: iosswiftuibuttonuikituiedgeinsets

解决方案


may be try this

button.contentHorizontalAlignment = .center

推荐阅读