How to Create Widgets With SwiftUI? An iOS App Development Guide
Learn a step-by-step detail-oriented guide by DEV IT app developers on how you can create customized Widgets with WidgetKit in SwiftUI.
Join the DZone community and get the full member experience.Join For Free
Apple introduced Widgets with the launch of iOS 14 at WWDC20. The developers can create customized widgets using the newly introduced WidgetKit, which is fully built with SwiftUI. This means, to incorporate the Widgets with your app, your app should be compatible with iOS 14 and you should have basic knowledge of SwiftUI to build it.
- XCode 12 or later
- iOS 14 or later
- Basic knowledge of SwiftUI
How To Create a Widget Extension in Your App?
1. Open your project in XCode
2. To create a new Widget, we are supposed to Add New Target in the workspace
You can Add New Target to the project by pressing the ‘+’ button as displayed in the above image. Once you press the ‘+’ button, It will display a dialogue with multiple options.
Select ‘iOS’ as a platform, and select ‘Widget Extension’ from the ‘Application Extension’ category, and press Next.
Here, you can add the appropriate name of your choice as Product Name. We’re keeping it as ‘DemoWidget’ for demo purposes.
There are two types of configurations: StaticConfiguration and IntentConfiguration. For the demo purpose, we are keeping StaticConfiguration for this Widget. So, please uncheck the checkbox as shown in the above image and press Finish.
And It’s done – you have successfully created a new Widget Extension. Please check the image below to see the changes.
XCode has added a new Target named DemoWidgetExtension in the TARGETS list, also one group has been added in the project name DemoWidget. Now, run the project keeping the DemoWidgetExtension target selected.
The result will be similar to the below image. Also, you can check multiple options by long-pressing the widget. Please follow the given steps
So we just completed widget creation. Now, let’s understand the code and modify it as per our needs.
How To Modify Widgets as per Requirement?
Please open the DemoWidget.swift file from the DemoWidget group from the left side of the XCode window. You will see some boilerplate code already added to that file. So, this is designed to make your work easy. So let’s understand it one by one.
There are a total of 5 structs inside the DemoWidget.swift file.
Provider: It is a struct conforming to protocol TimelineProvider. It is designed to decide the rendering timeline of the widget.
It contains 3 functions:
- func placeholder(in context: Self.Context) -> Self.Entry
It is used to pass placeholder data until the user opens the companion app and it loads the actual data in the widget.
- func getSnapshot(in context: Self.Context, completion: @escaping (Self.Entry) -> Void)
It is used to generate the preview snapshot of the widget in the widget gallery.
- func getTimeline(in context: Self.Context, completion: @escaping (Timeline<Self.Entry>) -> Void)
It expects a Timeline object and it is used to decide the timeline of the widget to reload it. There are multiple TimelineReloadPolicy available to use for the Timeline of the widget. Those are atEnd, never, after(_ date: Date).
SimpleEntry: It conforms to TimelineEntry. There is a required property date. Users can define other properties based on their requirements.
DemoWidgetEntryView: It is the View that will be displayed inside Widget.
DemoWidget: It conforms to Widget and it is mainly responsible for the Widget Extension. It has two properties, kind and body, body accepts WidgetConfiguration including configurationDisplayName and description.
DemoWidget_Previews: It conforms to PreviewProvider and is responsible for previewing Widget.
Now let’s modify the boilerplate code and try to load some English words with a meaning that automatically displays a new word every 5 seconds. First of all, let’s change the SimpleEntry struct as shown below:
We have added two new properties word and meaning to store values of word and meaning in each entry. Now, let’s move to Provider struct and update it same as below:
You can see, we have added some dummy entries in placeholder and getSnapshot(…). Let’s check getTimeline(…) for the actual changes.
I’ve added an array of words with meaning, later on, you can connect it with any other sources such as UserDefaults, JSON objects, Network API calls, or anything else.
I have prepared an entries array with multiple Entry objects that have a 5 seconds Timeline and added an offset to all of them so it will be displayed for 5 seconds one after the other.
So, the logical part is done. We have transported data to Widget. But to display the data we need to modify DemoWidgetEntryView. Please update it as shown below:
So, this is how it will display a widget in multiple sizes. Users can choose from any of them. This widget will update the word every 5 seconds. You can even fetch the data from any other sources or even configure the duration of transition of words by making the widget Configurable.
So, this is how you create widgets using Swift UI. Instead of going through the hard steps of development, you could simplify your process by approaching it professionally.
Published at DZone with permission of Brijesh Patel. See the original article here.
Opinions expressed by DZone contributors are their own.