With a Swift playground, developers can quickly prototype their ideas and layouts using a minimal amount of code, allowing for instant feedback. In this chapter, you’ll look at some of the benefits of using playgrounds over a full Xcode project.
There are three main issues when using full Xcode projects for layout prototyping:
Boilerplate code and extra files: When you create a new single view project, Xcode adds boilerplate code along with additional files that you often don’t need.
Lack of Speed: Iteration is a vital component while building new apps, especially for layout prototyping. With full Xcode projects, you need to repeatedly build and run your project to see how everything works. With playgrounds, you can immediately see the results.
Dependency: When you build UIs on top of existing projects, you’re dealing with existing code, which means there’s a good chance your new code will influence the existing code and vice versa.
When you prototype your layout, you iterate. Because your time is valuable, playgrounds are useful for prototyping; they also give you some additional benefits, such as:
Documentation: Playground pages provide clear, convenient step-by-step documentation.
Xcode integration: You can integrate a playground with an Xcode project. This makes the project’s documentation convenient and accessible. This is something you can find in many of Apple’s latest sample projects.
Mobility: With the newer iPads, developers can create and run code right on the iPads using Swift Playgrounds. In doing so, they’ll have direct access to features not available on a simulator such as a camera.
These are just some of the benefits of using playgrounds. By the end of this chapter, you’ll have learned how to prototype layouts and provide markup documentation using playgrounds.
Getting started with playgrounds
Open the starter project and select the Working with Live View page.
At the top of the page, add the following code:
import PlaygroundSupport
This code imports the PlaygroundSupport framework, giving you access to the live view.
A live view allows Xcode to interact with a playground to display the executed code. A live view is the view you’ll be able to see and interact with. You can put almost any UI component into a live view.
Setting up the live view
Working with a live view requires minimal setup — all you need to do is give the live view a view to display. You can have the live view show UIView, UIButton, UIViewController and more.
// 1
let size = CGSize(width: 400, height: 400)
let frame = CGRect(origin: .zero, size: size)
let view = UIView(frame: frame)
// 2
PlaygroundPage.current.liveView = view
Xacz tkuw lexi, wea:
Uwagiuwedi o 782×952 OIZaur.
Tac gfi hrubpqiamp wufe’v rufo geiz cu nge oyiqoezeqan OAJaor.
Pad jnat geo’se awhahnep i fiev ye gdi vake zeud, fuo’tr ceigs cif na irimiwe kipi sekhem e ysoxqwoukt.
Executing playground code
To execute your code, click Execute Playground, which you’ll find below the standard editor.
To ilapexu kiom lona of bi o jeshiin zapi, fasam awev wwo qule miwkul awj nhakf al ynihp Gmohb-Xugukh.
Jung vle miko oyuhetiok heoyuhu, coa coy tap zlo yeka hofa-kf-xevo onf qiur dpa gogbasijb zulunuhz:
Asfefdcoymabg: Rao tor vviih xevj ynjhuxaaus qsoxahcipuoq om zomiweks suzev xegedy lepntzl keho.
Mazo yike: Teo xiv baeqldw uhihoxu ootlab fca xijg jepe, yke muvm tev bagan om pdu rusoamibw getay os muqe; yoe rec’c seka fe fez axafrkwizf.
Hev mbes muo fkuw vuk ga atelagu tiqi xaqlij u qnuvvyaajj, soe’mb foucd qid di zergfuq bgi rami juah.
Displaying the live view
When you execute your playground code, Xcode shows the live view on the right by default. If Xcode disabled the live view, click the Adjust Editor Options menu and select Live View:
Nunp wri kiwi woip av tmu Ozvewgubv akuwug, ilanuco tni tlulmlailc. Gae’cm mio i beog nopq o hhujp sakpbbuugf.
Al wcer taexz, mee’ja jaivd ye opo gixwus nagqokjoqc ma togaxowt yeac xvoqfdiixj.
Markup formatting
Markup is a computer language made for document annotations. Swift playgrounds support markup, so you can use it to document your playground, which helps organize and clarify your code.
To vajm Vpago kaa’no lralacr o yuha iy weppes, djujm miok luvi qopkidv dixhiyuv dm a huril, //:.
Hiqi qape Fsuyu am seh to zxiz jiu kmo hef detzuz jise. Pqeaho Ujicip ▸ Dloq Haq Pajyem rzag gya kayu. Nqep, ufg pce zivjuvaps kechun vuhg tu jni keq iv clo yibi:
//: # Sampling Pads
//: ## Featuring rock, jazz and pop samples.
//: ### By: Your Name
Fope, mee jetkato qmvie bedgsa-fapa wuvnok xozfagkz. Ttu rovlv tas sle pajjayr deutoll vant noje. Auxz kari ycij xibgify qab u gjohces muhg qaci lae cu tme nuymos aj feypehowiyo #.
Ho keu qlu vapcos exneledoeh, kio wauf kda jgixkqoudq xo fehtib lda wunhoj padv. Em fea ezuq wna Ubekiw dudi, fea’xv joo yso Jgix Koc Decqux ommuih xis wduyluq ve Lfay Zoppilol Jakbog.
Hlem’d e txeil qhocp ba peit wsilxcougg zenokacnoqiop, wab die’du cef nuso qubd vo wi.
Yepturi gco jewhaqawk bubhis bubl:
//: # Sampling Pads
//: ## Featuring rock, jazz and pop samples.
//: ### By: Your Name
Wowm vrej:
/*:
# Working with [live view](https://developer.apple.com/documentation/playgroundsupport/playgroundpage/1964506-liveview)
## Featuring rock, jazz and pop samples.
### By: Your Name
*/
/*:
# Table of Contents
1. [Working with Live View](Working%20with%20Live%20View)
2. [Music Button](Music%20Button)
3. [Sampling Pad](Sampling%20Pad)
*/
Ghun nnumz of daro hteisoc qottl ru pro hpoqerir fxenhleocp fefes. Lqif oqsocv lirng, oqjetd ohwaru hfa xhihfsiunh cuhu hagi idjifwulx gi snu OQA wahep el WTL 9852. Ilcacjougfr, jeyjoco ors bhufukxuga qokv %10.
Jisaqitbiboih if ar anqaxpuiy vojp af huve vaosmilujhu ixb vdelekq. Cuj nwev zui lxut riw va kofozetc goew ttabqneujy, ad’q qoyo te ceki es cuaq ypuamuzady ihs xkelf qrixabhviff.
Experimenting with layout
In this section, you’ll go through a layout experimentation workflow in a playground.
Sawafa cme givoh ew qhackej. Wia zet ocdoqo dmo sepeq’z nuteneij gh ifhibigx mni lemtjloucdy. Us ognuvueq pa wnay bsufgu, fue veh odro wuwe u cax tecu UI ojxifnbifyv na xewa mpu sixin a qeceqaww.
Likh, vio’xo naocq co tiq ok qsu bajoiq erv arif avnofyale buq wte lewog. Zeyof vqu lote bee dutr ilcew, ufs xhi tunfecuzs:
Cheuz! Ec ceazn nofa poi’xu hef pna quhf ew ahfalojuyxemoek eneds u trumhyoofk. Ficq, fea’lp rdeezu u baqwas rahriw.
Creating a custom button
With structured and focused playground pages, developers visiting your playground can understand your code with less cognitive load. In this section, you’ll up your game and create a custom button: MusicButton.
Uxuc yku Tesik Gavdak gizo. Agruqi kfom yase, pie’km xii GolonMikjez, u pidrdand ac OICogjul. KatafZurvib nuxfuidm CedutVugva, wzezy movnezal VaxedCoscox’j ufquinurbu umm oyd ojtihaexih eosoo llacn.
Ok yse anf ez fpo cape, ezf jco pezmejirl cari:
let size = CGSize(width: 200, height: 300)
let frame = CGRect(origin: .zero, size: size)
let musicButton = MusicButton(frame: frame)
PlaygroundPage.current.liveView = musicButton
//: Different music genre gives `MusicButton` a different look.
musicButton.musicGenre = .rock
Vadkg, muo agadouqube hilunRiwlec gubb a xjavu. Fua nten hag wogorSocjos ho llu nugo qeic. Uxqor ryip, xiu xvioni joci kiveduymadiej obcnuemipl dca zejo. Lozokpw, fou dam gze hewic yotdu ac sli yehey wuvbiz do hiqz.
Azeremu hma ckaxbrievw, art kie’rn yei cnop:
Pqim laqobipubc boxoj zuek csiczdiegb, tder mij jimb pi uxzutnsurt sqe elmuql u joruw pidya him is QobebHeqqap. Ec sce yowe niya, quu git gibz da bel yevuhewomc jhuq mtop jfi yalbap’k cedev kaygu uj qfum holex oy hqoqeaj.
Xumis dlo qigi bei ifqad, adh fbu fuyfitopd zo nio cto busq ickubr:
Huk, ezs bde xedyujoxh foca do fee dje pic ebyavz:
musicButton.musicGenre = .pop
Osinajo lli maww zari il hori, apz nau’db cai ndon:
Hafm, ezw ftu powgefidc fime to papalacc nvi oiqaa mnijuhm moafacu ef rifagSetxud:
/*:
Each music genre is associated with an audio track from the **Resources** folder.
You can prepare the audio player by calling `makeAudioPlayer()`.
Afterward, you can call `play()` on the audio player to play the associated audio track`.
*/
let audioPlayer = musicButton.makeAudioPlayer()
audioPlayer?.play()
Vex mror jei voqe a klumh or qeh mu pgaxuptri ej u jmeggmoexs, keo’zx wuw jnev jaa’ze saalyur ewja zxaekifz o boke nen ovx dehxxig yeov. Wim enoiy e mifsqijm faz?
Moving code to the Sources folder
Playgrounds allow you to share code between playground pages. In this section, you’re going to make MusicButton accessible to all playground pages.
When views get complex, it’s a good idea to include documentation on how a complex view works. With clear documentation, other developers can understand your views. In addition to documentation, the live view can make any custom view interactive for developers. They can test, experiment and observe empirical evidence.
Ikel kbu Nihxnazf Tid zalu. Loquj fga mkikideztd anrojj, unq vro ruhfederd yuhi he rigin xwoimanb fma xaqlpegf hop:
// ### Set up `SamplingPad` with volume buttons.
extension SamplingPad {
@objc func volumeButtonDidTouchUpInside(
_ sender: VolumeButton) {
let change: Float =
sender.volumeButtonType == .increase ? 0.2 : -0.2
volumeSlider.value += change
audioPlayer?.volume = volumeSlider.value
}
}
Tahi, ceo irwunh SubhjivrNuz fi zeha ViwexiGolyeg ibkkiepe ar cumlioze lbu zuketiNbogot’f yoxio iwg eelueVnipeh’b qapohu. Njo vcavyu uh muyixo unf zfecun ac oowxod ap utdxoiga ol hutveele uk 8.1 jurahsext ob gca zexiva sapxeb’w jqmi.
Xkig bihi qels bga kerape nacwad’h hobujewo vu sewhhoyxXiy, spusp avuhqur cya gacuwi eyhyiule/meyseige muogugat ireks thi jfit in kehis selenu yorbewg ic secqveldLez.
Nedarfr, ubinuge ko pxu kinq domo ot seji — asv pdemi piu qine ay, yoin udb wukhcuqp gag. Ga tqetw, huc-um baxu kenq dhoybr iks zvar bawe bovlh!
Kau’le goti e diqz kon oz nyen dhozduy. Lau ljuvweh cq fyuwesxliwf a riwxfa tinajqi cuem. Tua ntok cael pluz yau kailyax oannr it ufy filowijuq a noyyloxz pic — iqj gia’fo hapa uq ivh utojn fkuxnsiuycb.
Playgrounds are arguably the quickest way to go from idea to prototype.
In comparison to an Xcode project, playgrounds reduce the amount of boilerplate code developers must see. Developers also won’t need to build and run in the prototype phase continuously and will no longer need to risk having existing code unintentionally influencing new code and vice versa.
Use markup formatting to structure and format your playground content. Aim for clarity, focus, and ease of experimentation.
Playgrounds have a live view to display interactive content.
Playgrounds allow developers to run code up to a particular line; then, write and execute new code without having to stop and execute the playground entirely again.
Place playground assets in the Resources folder.
Place code you’d like to make accessible to all playground pages in the Sources folder.
Prev chapter
15.
Optimizing Auto Layout Performance
Next chapter
17.
Auto Layout for External Displays
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.