ios - 约束似乎会改变 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)
])
}
}
图片
解决方案
您正在将旧框架方法与 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)
])
}
}
推荐阅读
- php - 如何删除codeigniter中的index.php?,我尝试了正常的技术,但没有奏效
- php - DoctrineORMEntityManager ::initializeProxy() 的声明必须与 ProxyManager\Proxy\LazyLoadingInterface::initializeProxy() 兼容:bool
- go - 具有缓冲作业和固定轮询间隔的工作池
- java - 过度依赖一个arrayList
- python - 如何使用 Python/Tweepy 将推文上传到 SQLite 数据库?
- css - CSS过渡不能从下到上工作
- python-3.x - 等价于 bash "|" 在python3中
- android - 在 android webView 中接收 net::ERR_CONTENT_LENGTH_MISMATCH 错误
- django - 对 API 相关性和 Django 感到困惑
- java - 通过 ftp 发送的 JAVA Tar