How to use Link in WidgetKit to define arbitrary regions, not just text links?

1k views Asked by At

In the session "Widgets Code Along Part 2" in WWDC 2020, the presenter says:

Widgets do not have animation or custom interactions, but we can deep link from our widget into our app. SystemSmall widgets are one large tap area, while systemMedium and systemLarge can use the new SwiftUI link API to create tappable zones within the widget.

This suggests that I should be able to designate regions of my widget as tappable that lead to a given URL in my app. But the Link API just takes a string title and a destination URL - it doesn't appear to be able to embed other arbitrary views like images.

How do I use the Link API to designate regions of my widget as tappable, instead of just text links?

1

There are 1 answers

0
fruitcoder On BEST ANSWER

The type definition of Link is actually struct Link<Label> where Label : View so the only constraint to Label is that it conforms to the View protocol (despite the name indicating otherwise). My preferred initializer is init(destination:, label:) so you can embed every view in the view builder like this:

Link(destination: URL(string: "some://dest")!) {
  HStack {
    Text("I'm part of the tappable area")
    Text("Me too")
  }
}

You can actually see this in action in the Emoji Rangers project from Apple (check AllCharactersView.swift.