SwiftUI. Add specific action in Widget

Hi all! Check out another short how-to on SwiftUI.

This time I want to let you know how to add a specific action on your Widget.

Recently I have been working on the app that has a list on a widget. Each item in the list should be tappable and perform a specific action on item tap.

There are two types of actions you can add to your widget:

  1. General action for the entire widget. This can be achieved by adding the following modifier:

In this case if you tap on a widget, your app will receive an URL you pass to the .widgetUrl() modifier.

  1. Action on specific views. This can be achieved by wrapping any View in Link:
Link(destination: URL.init(string: "com.foo/bar")!) {
Image(systemName: "doc.on.clipboard.fill")

In this case if you tap on Image(systemName: "doc.on.clipboard.fill")app will be opened by the URL passed to the Link which wrapped that Image

In order to retrieve the info you passed via URL, you need to use .onOpenURL function:

.onOpenURL { url in
// Parse your url here to get the passed info

That’s it. Happy coding!




Founder of Pills.Kit, Proximodoro and WidgetLingo apps

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Copy-on-Write in Swift Collections

Highly intelligent iOS developers use enum with properties. Don’t make your code seem dull.

iOS — Auto-Layout — Less than / Greater than constraints

How to display an image picker controller using Swift

12-year-old programmer tackles Apple’s first student coding contest.

Does Ring Work With HomeKit? We Asked a Expert and Here’s What He Had to say!‍

Modular Architecture on iOS and how I decreased build time by 50%.

Apple iOS 14 Merged Several Android Features To Make The iPhone Better

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
Artem Mihelson

Artem Mihelson

Founder of Pills.Kit, Proximodoro and WidgetLingo apps

More from Medium

SwiftUI. How To pass Binding variable to PreviewProvider

Display async image protected by header-based authentication in SwiftUI

How to Customize SwiftUI Chat Messaging App Powered by Stream

Stack Navigation on macOS in SwiftUI

Column and stack navigation styles compared