Ferran Maylinch Ferran Maylinch - 3 months ago 42
iOS Question

How can I display views using autolayout constraints in Xcode playground?

I am trying to display views configured with autolayout constraints in XCode playground, but it doesn't seem to work. It's like playground ignores the constraints completely, and I can't find information about this issue anywhere.

Here's the code I tried:

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)


Thanks in advance

Answer

Typically you need to call layoutIfNeeded before you can actually see your view. That being said you will probably find it more rewarding to import XCPlayground and use XCPShowView("view",view) to have the playground render your view live. This is especially powerful when you start prototyping animations etc. Here's a link to further expand on this

Update

As of Xcode 7 and the introduction of Playground pages its now more appropriate to set the livePageView of your playground page:

XCPlaygroundPage.currentPage.liveView = view
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true