首页 > 解决方案 > 约束似乎会改变 UIButton 框架大小

问题描述

背景

我正在尝试创建一个宽度为 300 像素、高度为 200 像素的 UIButton。

然后,我试图定位 UIButton 水平居中,距离底部 50 像素。

在iOS模拟器中运行代码,结果出乎意料,按钮高宽不正确,UIButton出现裁剪。下图。


问题

必须对以下代码进行哪些更正,以便 UIButton 布局正确定位并保留正确大小的 UIButton 框架?


代码

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addButton1()
    }

    func addButton1() {
        let myButton1 = UIButton(type: UIButton.ButtonType.custom)
        myButton1.frame.size = CGSize(width: 300, height: 200)
        myButton1.setTitle("Hello", for:UIControl.State())
        myButton1.backgroundColor =  .blue
        view.addSubview(myButton1)
        myButton1.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            myButton1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myButton1.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50)
        ])
    }

}

图片

在此处输入图像描述

标签: iosswiftuibuttonnslayoutconstraint

解决方案


您正在将旧框架方法与 AutoLayout 混合使用,但这是行不通的。我建议坚持使用 AutoLayout,因此您的代码可能是:

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    addButton1()
  }

  func addButton1() {
    let myButton1 = UIButton(type: UIButton.ButtonType.custom)
    myButton1.setTitle("Hello", for:UIControl.State())
    myButton1.backgroundColor =  .blue
    view.addSubview(myButton1)
    myButton1.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
      myButton1.widthAnchor.constraint(equalToConstant: 300),
      myButton1.heightAnchor.constraint(equalToConstant: 200),
      myButton1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      myButton1.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50)
    ])
  }

}

推荐阅读