Austin Rude's Blog

Drawing custom views in Swift Playgrounds

Easy template to start working on a custom view in Swift Playgrounds

Getting the details right in a custom view can require tens or even hundreds of iterations. Building an iOS project, loading the app in the simulator, and checking the results is just too slow.

Swift Playgrounds allow you to write your drawing code, and see your results almost instantaneously in Xcode. Just use the following as a starting template, and start drawing!

Make sure you have the Assistant Editor open (View->Assistant Editor->Show Assistant Editor) to see the live view

Playground Code

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class CustomView: UIView {
    override func draw(_ rect: CGRect) {
        super.draw(rect)

        // draw stuff
        let rect = UIBezierPath(roundedRect: CGRect(x: 150, y: 150, width: 100, height: 100), cornerRadius: 5.0)
        UIColor.green.set()
        rect.fill()
    }
}

let containerView = CustomView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
containerView.backgroundColor = UIColor.blue

PlaygroundPage.current.liveView = containerView

Playground Screenshot

Playground Screenshot

Tips

  • This is also a convenient way to work on UIView animations
  • UIView, and UIViewController both conform to the PlaygroundLiveViewable protocol and can be set as the liveView
  • NSView/NSViewController also conform to PlaygroundLiveViewable!
  • Save the code above to a Snippet in Xcode
  • Use the View->Assistant Editor->Assistant Editor On Bottom menu option for a better Xcode editor layout (unlike my screenshot)
  • There's a boolean needsIndefiniteExecution on the PlaygroundPage class. Use it to tell the playground to not immediately kill execution (useful for async code, animations, etc.)

One interesting thing revealed in the open-source release of the Kickstarter iOS app, is that they have Playgrounds for most screens in the app. See Kickstarter for iOS - GitHub if you're curious.

References

  • https://developer.apple.com/reference/playgroundsupport
  • https://github.com/kickstarter/ios-oss

Tagged Xcode Playgrounds , Swift , Xcode , Playgrounds and Views