Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Use App Extensions in SwiftUI
Written by Team Kodeco

Have you ever wanted to add extra features to your app without bloating its main codebase? Or have you wanted to leverage functionality provided by another app on your device to enhance yours? Well, with app extensions in SwiftUI, you can!

App extensions, such as widgets, iMessage extensions and custom keyboard extensions, allow you to add extra functionality to your app. And the best part is that you can develop them separately from your app, which makes it easier to maintain and enhance their codebases.

Let’s explore how to create an app extension in SwiftUI with a simple example. Say you want to create a widget that displays the current time in a fancy way.

In Xcode, choose FileNewTarget. Select the iOS tab and then choose Widget Extension from the Application Extension section. Name your new target FancyTimeWidget. Because widgets can only be programmed with SwiftUI, you won’t need to choose an interface here. Activate the new scheme when prompted.

Once the widget target is created, open FancyTimeWidget.swift inside the new FancyTimeWidget group and replace the block beginning with struct FancyTimeWidgetEntryView with the following code:

struct FancyTimeWidgetEntryView : View {
  var entry: Provider.Entry

  var body: some View {
    Text(entry.date, style: .time)
      .font(.largeTitle)
      .foregroundColor(.red)
  }
}

Here’s what your preview should look like:

A fancy time widget on iOS.
A fancy time widget on iOS.

This code creates a fancy time view with a red font that displays the current time, a widget configuration that defines the widget’s behavior and appearance, and a time provider that supplies data to the widget.

There’s lots more to learn about widgets and other app extensions. One good starting point is Creating a widget extension in Apple’s developer documentation.

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.
© 2024 Kodeco Inc.