【发布时间】:2021-10-09 08:43:09
【问题描述】:
背景
我正在尝试创建一个宽度为 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)
])
}
}
图片
【问题讨论】:
标签: ios swift uibutton nslayoutconstraint