Complications(Widgets) For WatchOS — SwiftUI

Watch Complications:

WidgetKit provides a modern API for creating and updating glanceable elements — making it an ideal fit for watchOS complications. Because WidgetKit’s design was inspired by ClockKit, if you’ve already designed ClockKit complications for your app, the process should feel familiar. Similarly, if you’re already using widgets for iOS, you can quickly and easily set up WidgetKit complications for a watchOS app. In many cases, you can use the same code to display WidgetKit complications in watchOS and widgets on the Lock Screen on iPhone — from developer portal.

Requirements:
XCode 14 (Beta)
iOS 16.0 and WatchOS 9.0

Implementation:

Create watch only app by creating new project and selecting watchOS.

And select Watch only option and create a project.

Now add widget extension to it.

Make sure uncheck the “include Configuration intent” option.

And Activate the created extension.

Here am gonna create a basic list view for metal prices such as Gold, Silver, Platinum and Copper per gram.

Now will create a row View.

struct RowView: View{@State var textValue: String@State var img: Stringvar body: some View {HStack(){ZStack{Circle().fill(Color.white).frame(width: 35, height: 35)Image(img).resizable().frame(width: 25, height: 25)}Text(textValue).frame(width: WKInterfaceDevice.current().screenBounds.size.width*0.5)}.frame(width: WKInterfaceDevice.current().screenBounds.size.width*0.8, height: 45)}}

Now we gonna pass value to the list in ContentView. And add these rows to it.

struct ContentView: View {@StateObject private var viewModel = NetWork()var body: some View {VStack {//Add rows here
}
}
}

Now Run the App Scheme.

now will Move to Extension Part. Here we gonna create separate view for each type of widget family. The families are
1. accessoryCircular
2. accessoryInline
3. accessoryCorner
4. accessoryRectangular

@Environment(\.widgetFamily) private var family

We can fetch family type and assign specific View for each widget family.

switch family{case .accessoryCircular://Code for Circularcase .accessoryCorner://Code for Cornercase .accessoryInline://Code for Circularcase .accessoryRectangular://Code for Rectangular@unknown default:Text("")}

Now Run the code and try all the widget families by choosing different watch faces.

Above is accessory corner widget. Got to complication and add the widget from list.

Similarly for all families. Here i just show gold price by fetching data from API.

For more info follow me on twitter.

Happy Coding💖!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store