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

The provided solutions were not useful for me. I wanted a view in which I could work with constraints. To achieve that I had to create a containerView with a CGRect base and adding constraints to it as well. Everything else was not successful. So I got a viewable base and was able to add views just with constraints.

Setup 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

Place View in ContainerView with constraints:

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

This creates this view:

enter image description here


That being said you can use the liveView property of PlaygroundPage to preview your UI.

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView

Here's a link that expands on this further.

If its not working you may need to trigger a layoutIfNeeded but that shouldn't really solve the issue since Swift 4

Also, include translatesAutoresizingMaskIntoConstraints = false on your view. Like:

import PlaygroundSupport

myLiveView.translatesAutoresizingMaskIntoConstraints = false
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = myLiveView