我试图在 XCode playground 中显示配置了 autolayout 约束的 View ,但它似乎不起作用。就像 playground 完全忽略了约束,我在任何地方都找不到关于这个问题的信息。
这是我试过的代码:
let view = UIView()
view.frame = CGRectMake(0, 0, 400, 200)
view.backgroundColor = UIColor.lightGrayColor()
let label = UILabel() // I can only see the label if I set a frame
// UILabel(frame: CGRectMake(0, 0, 200, 50))
label.backgroundColor = UIColor.greenColor()
label.text = "I am a label"
label.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(label)
let views = ["label":label]
let options = NSLayoutFormatOptions(0)
let cs1 = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[label]-|", options: options, metrics: nil, views:views )
let cs2 = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-[label]-|", options: options, metrics: nil, views:views )
view.addConstraints(cs1)
view.addConstraints(cs2)
提前致谢
最佳答案
也就是说,您可以使用 PlaygroundPage
的 liveView
属性来预览您的 UI。
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView
这是一个 link进一步扩展了这一点。
如果它不起作用,你可能需要触发一个 layoutIfNeeded
但自 Swift 4 以来,这并不能真正解决问题
此外,在您的 View 中包含 translatesAutoresizingMaskIntoConstraints = false
。喜欢:
import PlaygroundSupport
myLiveView.translatesAutoresizingMaskIntoConstraints = false
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView
关于ios - 如何在 Xcode playground 中使用自动布局约束显示 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333323/