The playground timeline can display objects as well as numbers and simple strings. It is possible to load and view images in a playground using classes such as UIImage
(or NSImage
on OS X). These are known as QuickLook supported objects, and by default include:
To show a colored label, a color needs to be obtained first. When building against iOS, this will be UIColor
; but when building against OS X, it will be NSColor
. The methods and types are largely equivalent between the two, but this chapter will focus on the iOS types.
A color can be acquired with an initializer or by using one of the predefined colors that are exposed in Swift using methods:
import UIKit // AppKit for OS X let blue = UIColor.blueColor() // NSColor.blueColor() for OS X
The color can be used in a UILabel
, which displays a text string in a particular size and color. The UILabel
needs a size, which is represented by a CGRect
, and can be defined with an x
and y
position along with a width
and height
. The x
and y
positions are not relevant for playgrounds and so can be left as zero:
let size = CGRect(x:0,y:0,width:200,height:100) let label = UILabel(frame:size)// NSLabel for OS X
Finally, the text needs to be displayed in blue and with a larger font size:
label.text = str // from the first line of the code label.textColor = blue label.font = UIFont.systemFontOfSize(24) // NSFont for OS X
When the playground is run, the color and font are shown in the timeline and available for quick view. Even though the same UILabel
instance is being shown, the timeline and the QuickLook values show a snapshot of the state of the object at each point, making it easy to see what has happened between changes.
Images can be created and loaded into a playground using the UIImage
constructor (or NSImage
on OS X). Both take a named
argument, which is used to find an image with the given name from the playground's Resources
folder.
To download a logo, open Terminal.app
and run the following commands:
$ mkdir MyPlayground.playground/Resources $ curl http://alblue.bandlem.com/images/AlexHeadshotLeft.png > MyPlayground.playground/Resources/logo.png
An image can now be loaded in Swift with:
let logo = UIImage(named:"logo")
The loaded image can be displayed using QuickLook or by adding it to the value history:
It is possible to use a URL to acquire an image by creating an NSURL with NSURL(string:"http://...")
, then loading the contents of the URL with NSData(contentsOfURL:)
, and finally using UIImage(data:)
to convert it to an image. However, as Swift will keep re-executing the code over and over again, the URL will be hit multiple times in a single debugging session without caching. It is recommended that NSData(contentsOfURL:)
and similar networking classes be avoided in playgrounds.