Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

Writing Your First Widget for iOS

Sagun Raj Lage
Level Up Coding
Published in
11 min readJun 25, 2020

--

Source: WWDC20

If you’ve been following WWDC20, then you totally understand how huge this edition of WWDC has been for the whole Apple ecosystem, users, and developers. With the announcement of iOS 14, many handy features are on their way to spice up the iOS experience. One of such features is Widgets.

I know this doesn’t sound new for Android users, but this definitely is great news for iOS users. Now, developers can create widgets of their applications by making use of the new WidgetKit framework. As of now, it is in Beta and available in Xcode 12 Beta and above.

Note: You will need Xcode 12 Beta or above to be able to create Widgets.

Now, let’s start writing our very first widget for iOS. For that, let’s create a new SwiftUI project. I’m naming it CountrySelector. This application will display the flags of some countries and when the user taps on any flag, the details of that particular country will be displayed in the widget of the application.

Sneak peek of how the widgets will look like. In the screenshot, the medium sized and large sized widgets are shown.
Creating a new SwiftUI project

After creating your project, the project structure will look something like this:

Project structure

First, let’s create a model, Country. It will be a struct that will hold a country’s details like name, flag and continent. Let’s make it conform to Codable and Identifiable protocols since we want to perform encode-decode operations and later perform an iteration using ForEach respectively. Since we made our model conform to Identifiable, we will be asked to add an id property, which is a computed property returning the value of name, in the model. Hence, after adding everything, the final code will look like this:

--

--

Written by Sagun Raj Lage

Author of Getting Started with WidgetKit (2021) | iOS Engineer | Full Stack Engineer