Use Gestures: Even in Swift Playgrounds

You can use gestures for code written in Playgrounds!

Image for post
Image for post
Photo by Derick McKinney on Unsplash

Did you know that Playgrounds has support for gestures? No? Read on and find out!

Difficulty: Beginner | Easy | Normal | Challenging

You might be aware that Swift’s Playgrounds are a great way to write and test code quickly and easily.

Did you also know you can use liveView and gestures to create a fully functioning app?

Let’s go!

The end product

You’ll be able to drag and drop a shape on the background. Like (you know) in a very simple App. However — this will be happening in Playgrounds.

Image for post
Image for post

The explanation

Setting up the Playground

PlaygroundSupport has all you need to make the most of your playground experience.

By this I mean you can add

import PlaygroundSupport

which enables a collection of great features. One of these is to (assuming we have a MyViewController() UIViewController (or even UIView) instantiated somewhere in the project).

PlaygroundPage.current.liveView = MyViewController()

Using a Gesture

For this tutorial I’ve picked a pan gesture because it’s, you know, fun.

Dragging around a UIView — why wouldn’t you?

To do so we set up the pan recogniser in viewDidLoad() with the following couple of lines

Image for post
Image for post
Click for Gist

which calls our method to handle the pan:

Image for post
Image for post
Click for Gist

And.. that’s it.

You can click on the view and drag it around the screen!

Setting up the reset of the project

If you would want a guide to setting up the whole project, I can tell you that using loadView() is the right way to go, but for a less subtle hint here is the whole code for a copy-pasta opportunity for you. Of course you can also download the code using the Gist below:

Image for post
Image for post
Click for Gist

Conclusion:

We’v

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store