Building your first widget - Step 1
It was pretty cool when Apple gave us widgets with iOS 14. Finally we could customize our home screens with something more than just app icons! This is a simple walkthrough of how to add a widget to your app & what to put in the widget template code Apple creates for you. Letâs get started.
In this article weâll add a basic widget to an existing project, then get it running on the simulator.The first step is to create your widget target - so (1) click on your project file and (2) click the plus button in the target column.
Next, select make sure iOS is selected as the platform, and select âWidget Extensionâ as the target type. I like to use the filter field in the top right to quickly find what Iâm looking for. Click next.
Give your widget a name (a good convention is ending the name with âWidgetâ so itâs obvious what the targetâs purpose is). You can uncheck âInclude Configuration Intentâ for now (donât worry, another article will talk about widget intents & how to use them). Click finish.
Lastly, activate the scheme when Xcode prompts you (if it doesnât prompt you & the scheme isnât created, go to Product > Scheme > Manage Schemes⊠and click âAutocreate Schemes Nowâ)
Nice! Your widget extension target is ready to go. At this point you can build and run to preview the widget - just make sure the widget extension scheme is active:
Hereâs what you should see - the default template code simply shows a timestamp:
If youâd like to preview the widget at another size, you can do that pretty easily by passing an environment variable in the scheme. Click the widgetâs scheme name (1) and then click âEdit Scheme...â (2)
Make sure that the run scheme is selected. Xcode should already provide you with a _XCWidgetFamily environment variable set to âmediumâ. Just check the box next to that entry and click close.
Hit run one more time to see the medium widget on the simulator.
Thatâs it for step one - adding the widget extension target is pretty easy. Now we can start the real work of customizing the widget UI and data. For that, continue to step 2.