代码创建 UI 组件时出现的错误 UILayoutConstraint translatesAutoresizingMaskIntoConstraints: Bool

来源:互联网 发布:java游戏编程入门pdf 编辑:程序博客网 时间:2024/06/05 02:16

本文主要是说 UIView 的一个属性值 translatesAutoresizingMaskIntoConstraints: Bool

情况是这样的:我在学 UILayoutConstraint,然后在一个 UIViewController 中代码新建一个 UIButton,我把 button 添加到 view 中,设置其大小和约束,到执行的时候却没有按照约束的显示,反而在控制台出现约束错误信息。

代码:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 100))// 定义按钮外观button.layer.cornerRadius = 20button.layer.borderWidth = 1 / UIScreen.main.scalebutton.layer.borderColor = UIColor.lightGray.cgColor// 按钮状态button.titleLabel?.font = UIFont.systemFont(ofSize: 40)button.setTitleColor(UIColor.black, for: .normal)button.setTitleColor(UIColor.lightGray, for: .highlighted)button.setTitle("正常", for: UIControlState.normal)button.setTitle("高亮中", for: UIControlState.highlighted)view.addSubview(button)// 按钮约束button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = truebutton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = truebutton.heightAnchor.constraint(equalToConstant: 100).isActive = truebutton.widthAnchor.constraint(equalToConstant: 200).isActive = true

手机上的结果却是这样的:(看不清 右击在新窗口中打开图片)

错误结果

控制台错误:(看不清 右击在新窗口中打开图片)

控制台错误信息

怎么弄都不对,我以为我写的约束有问题,困了我一整天时间,在静下心来查看错误的时候终于看到了答案。像错误信息中说的 注意 translatesAutoresizingMaskIntoConstraints 这个属性,如下图,然后查阅 API,得到的信息是,当用代码创建控件的时候,translatesAutoresizingMaskIntoConstraints 这个属性的值是 true,也就是说,在控件创建时,系统会自动根据控件的大小等生成关于这个控件的 约束,这就解释了为什么提示约束冲突,因为当你的 translatesAutoresizingMaskIntoConstraints 为 true 时,该控件已经有健全的约束了,你在代码中添加的那些自然会与已经存在的冲突。

API 信息 (看不清 右击在新窗口中打开图片)

在图形化编辑的界面中,控件的这个属性值是 false,用代码生成的控件,这个属性值默认是 true
这个值来决定是否根据控件的大小自动生成约束。

API

知道为什么之后,修改代码:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 100))button.translatesAutoresizingMaskIntoConstraints = false // 添加的内容button.layer.cornerRadius = 20button.layer.borderWidth = 1 / UIScreen.main.scalebutton.layer.borderColor = UIColor.lightGray.cgColorbutton.titleLabel?.font = UIFont.systemFont(ofSize: 40)button.setTitleColor(UIColor.black, for: .normal)button.setTitleColor(UIColor.lightGray, for: .highlighted)button.setTitle("正常", for: UIControlState.normal)button.setTitle("高亮中", for: UIControlState.highlighted)view.addSubview(button)button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = truebutton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = truebutton.heightAnchor.constraint(equalToConstant: 100).isActive = truebutton.widthAnchor.constraint(equalToConstant: 200).isActive = true

得到结果:

正常结果

关于 UILayoutConstraint 的知识看这里 http://blog.csdn.net/KimBing/article/details/78541677

阅读全文
0 0
原创粉丝点击