如何在Xcode游乐场中使用自动布局约束显示视图?

Fer*_*nch 10 xcode ios autolayout swift swift-playground

我试图在XCode 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)
Run Code Online (Sandbox Code Playgroud)

提前致谢

Dan*_*sko 17

话虽如此,您可以使用预览UI 的liveView属性PlaygroundPage.

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView
Run Code Online (Sandbox Code Playgroud)

这是一个进一步扩展的链接.

如果它不起作用你可能需要触发一个layoutIfNeeded但是这不应该真正解决自Swift 4以来的问题

另外,请translatesAutoresizingMaskIntoConstraints = false在您的视图中添加.喜欢:

import PlaygroundSupport

myLiveView.translatesAutoresizingMaskIntoConstraints = false
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView
Run Code Online (Sandbox Code Playgroud)


Wal*_*ite 5

提供的解决方案对我没有用。我想要一个可以处理约束的视图。为了实现这一点,我必须创建一个带有 CGRect 基的 containerView 并为其添加约束。其他一切都没有成功。所以我得到了一个可见的基础并且能够添加带有约束的视图。

设置容器视图:

let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 600, height: 400))
containerView.backgroundColor = UIColor.lightGray
containerView.translatesAutoresizingMaskIntoConstraints = false

PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = containerView

containerView.widthAnchor.constraint(equalToConstant: 600).isActive = true
containerView.heightAnchor.constraint(equalToConstant: 400).isActive = true
Run Code Online (Sandbox Code Playgroud)

将视图放置在具有约束的 ContainerView 中:

let myView = UIView(frame: .zero)
myView.backgroundColor = .green
myView.translatesAutoresizingMaskIntoConstraints = false

containerView.addSubview(myView)

myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 200).isActive = true

myView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
Run Code Online (Sandbox Code Playgroud)

这将创建此视图:

在此处输入图片说明