我创建了一个只有两个视图的游乐场项目:屏幕中心有一个标签,屏幕下方还有一个按钮。当我启动这个例子时,一切都很好。为什么布局引擎在这个例子中踢入?
但是,只要将布局约束添加到标签视图,那么按钮视图就跳转到屏幕顶部!
Nota Bene:我在两个视图上都使用了translateAutoresizingMaskIntoConstraints = false
。
这里是没有限制的代码:
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
let liveview = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
let button = UIButton(frame: CGRect(x: 123.5, y: 566, width: 50, height: 50))
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("BUTTON", for: .normal)
button.backgroundColor = UIColor.darkGray
button.sizeToFit()
liveview.addSubview(button)
let label = UILabel(frame: CGRect(x: 134.75, y: 289.75, width: 50, height: 50))
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.blue
label.text = "LABEL"
label.sizeToFit()
liveview.addSubview(label)
PlaygroundPage.current.liveView = liveview
这里是结果。这是预期的,没有限制。请注意按钮视图的位置:它位于屏幕的底部。
现在我增加了约束至标签视图。这个添加的结果是Button View跳到了屏幕的顶部!以下是相应的代码,结果如下:
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
let liveview = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 600))
let button = UIButton(frame: CGRect(x: 123.5, y: 566, width: 50, height: 50))
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("BUTTON", for: .normal)
button.backgroundColor = UIColor.darkGray
button.sizeToFit()
liveview.addSubview(button)
let label = UILabel(frame: CGRect(x: 134.75, y: 289.75, width: 50, height: 50))
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.blue
label.text = "LABEL"
label.sizeToFit()
liveview.addSubview(label)
NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: liveview, attribute: .centerX, multiplier: 1.0, constant: 0.0).isActive = true
print(liveview.constraints)
PlaygroundPage.current.liveView = liveview
如果你有兴趣,这里存在打印限制名单的结果,这证实了的按钮来查看有没有相关的约束:
[<NSLayoutConstraint:0x60000008d890 UILabel:0x7fc2c3f06c20'LABEL'.centerX == UIView:0x7fc2c3d030c0.centerX (active)>]
我的问题是:为什么布局引擎移动的图,而没有相关的约束。