Working with live views in Swift Playground

Prototype faster in Swift Playground without Projects

When working on prototypes it is easy to create a new Playground to experiment on views. This makes the development really fast and easy. This method is much faster than creating a new XCode Project for prototyping.

Below is the code I use in Swift Playground


import UIKit
import PlaygroundSupport

let f = CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0)
let v = UIView(frame: f)
v.backgroundColor = UIColor.yellow

PlaygroundPage.current.liveView = v

 

Then, to see the live view, select ViewAssistant EditorShow Assistant Editor

Show Assistant Editor in XCode

 

And then select Timeline option to see the live view.

Show Playground Timeline in Assistant Editor (XCode)

 

Later, we will add UIView with red background color as sub-view to test live updates.


// will be adding red view as sub view
let redView = UIView(frame: CGRect.zero)
redView.translatesAutoresizingMaskIntoConstraints = false
redView.backgroundColor = UIColor.red

v.addSubview(redView)

redView.centerXAnchor.constraint(equalTo: v.centerXAnchor, constant: 0.0).isActive = true
redView.centerYAnchor.constraint(equalTo: v.centerYAnchor, constant: 0.0).isActive = true
redView.widthAnchor.constraint(equalToConstant: 15.0).isActive = true
redView.heightAnchor.constraint(equalToConstant: 15.0).isActive = true

 

And finally, see the updates.

See live updates in Playground (XCode)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s