Is there a way to work with UIKit within the context of a SwiftUI ViewModifier?
I would like to drop to UIKit here:
struct MyViewModifier: ViewModifier {
func body(content: Content) -> some View {
// Work on `content` using UIKit here.
// E.g. I would like to add a subview or CALayer to the existing `content` view
}
}
If you want to add a
UIViewto your SwiftUI view hierarchy, wrap it in aUIViewRepresentable. You can learn more in the WWDC 2019 session Integrating SwiftUI starting at 8m08s.If you want to add a
CALayer, you'll need to add it as a sublayer of aUIView's layer, and host thatUIViewusingUIViewRepresentable.Based on your question title, “Access the underlying UIKit view from a SwiftUI View Modifier”, I wonder if you think each SwiftUI view has a corresponding
UIView. It doesn't. SwiftUI can use a single (private, custom)UIViewto draw many SwiftUI views. Let's take a look.Here's a
UIViewRepresentablethat wraps a customUIViewsubclass. The subclass does just one custom thing: it prints the UIKit view hierarchy when it's moved to a window.I'll use it like this:
Here's the output (using Xcode 15.0 beta 2):
We can see here that SwiftUI does all the drawing for the
VStackand its subviews with just two instances ofUIViewsubclasses (the ones whose names start with_TtGC7SwiftUI). It doesn't even turn theToggleinto aUISwitch.