Thursday, December 18, 2014

Work with UIKit UIImage in XCode 6.1 Swift Playground

XCode 6.1 was one of the finalists of the Dr. Dobb’s Jolt Awards 2015: Coding Tools. The Playground introduced in XCode 6 is extremely useful to easily test your Swift code snippets.

However, there is some confusion about the possibility of working with some UIKit classes and check the results in the Playground.

You can create instances of many UIKit classes in the Playground and check the results at the right-hand side of your code snippets. In this case, I’ll provide you an example of how to create UIImage, CGRectMake, and UIButton instances. Then, I will set a title for the button, change the title’s color and finally set a background image.

After you create a new Swift Playground that targets iOS in XCode, select View | Utilities | Show File Inspector. Check the value for Resource Path below Playground Settings. In my case, the Resource Path is /Users/gaston/Documents/GastonHillarPlayground.playground/Resources. Thus, if you want to load an image within the Playground, just copy it to the folder specified in Resource Path. In my case, I just want to load an up arrow image, and therefore, I copy Arrow-Phone.png to the /Users/gaston/Documents/GastonHillarPlayground.playground/Resources folder.

Swift Playground that targets iOS in XCode, select View | Utilities | Show File Inspector.

Then, you can enter the following code and use either the Quick View eye or the Circle with the Plus (+) sign to check the visual results.

import UIKit

let image = UIImage(named: "Arrow-Phone.png")

let rect = CGRectMake(0, 0, 300, 100)

let button = UIButton(frame: rect)

button.setTitle("Up", forState: UIControlState.Normal)

button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)

button.setBackgroundImage(image, forState: UIControlState.Normal)

The following screenshot shows the results of clicking the Circle with the plus (+) sign for many code snippets and the visual results displayed at the right-hand side. Don’t forget to copy the images to the Resource Path folder. It’s the easiest way to make the Playground display images.
Work with UIKit UIImage in XCode 6.1 Swift Playground