Designing Interactive Interface Objects in Playgrounds - Swift 2.0, Xcode 7 and Interface Builder - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 1. Swift 2.0, Xcode 7 and Interface Builder

1.15 Designing Interactive Interface Objects in Playgrounds

Problem

You want to design a view the way you want, but don’t want to compile your app every time you make a change.

Solution

Use storyboards while designing your UI, and after you are done, put your code inside an actual class. In IB, you can detach a view so that it is always visible in your playground while you are working on it, and any changes you make will immediately be shown.

Discussion

Create a single view app and add a new playground to your project, as shown in Figure 1-5.

Figure 1-5. Add a new playground to your project

Write code similar to this to create your view:

import UIKit

var view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))

view.backgroundColor = UIColor.greenColor()

Now on the right hand side of the last line of code that you wrote, you should see a + button. Press that (see Figure 1-6).

Figure 1-6. Press the little + button to get your view right onto your playground

By pressing that button, you will get a live preview of your view inside your playground. Now you can continue changing your view’s properties and once you are done, add a new preview of your view, so that you can compare the previous and the new states (see Figure 1-7). The first view shown has only the properties we assigned to it up to the point that view was drawn. The second view has more properties, such as the border width and color, even though it is the same view instance in memory. However, because it is drawn at a different time inside IB, it shows different results. This helps you compare how your views look before and after modifications.

Figure 1-7. Two versions of a view

See Also