Custom UIHostingController


In the previous “How to use SwiftUI in UIKit” post I failed to do a custom subclass of UIHostingController, today I going to show how to do it (It quite easy I don’t know why I can’t do it at that time).

The problem

When you want to use SwiftUI in Storyboard IBSegueAction should suffice for most cases, but a subclass of UIHostingController also got its merit.

The problem I found which I can’t figure out a way to accomplish with IBSegueAction is when I try to assign one on UITabBarController‘s root view controllers as SwiftUI.

A problem

If I want to replace the second view controller with SwiftUI, I can replace the second view controller with UIHostingController, but no controller can listen for IBSegueAction. I tried assigning it to custom UITabBarController, but it didn’t work.

Expected result

Solution

From Apple’s Xcode beta release notes

You can add SwiftUI hosting controllers, such as UIHostingController, to connect a storyboard controller flow to a hosting controller that manages a SwiftUI view hierarchy. You can populate the contents of a hosting controller in Interface Builder by providing a custom subclass that programmatically sets the rootView of the controller. 

So to solve this, we first create a subclass of UIHostingController

Create custom UIHostingController

then customized it like this.


struct SecondView: View {
  var body: some View {
      VStack {
          Text("Second View").font(.system(size: 36))
          Text("Loaded by SecondView").font(.system(size: 14))
      }
  }
}

class SecondViewHostingController: UIHostingController<SecondView> {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder, rootView: SecondView())
    }
}

Then assign this custom class to UIHostingController in the storyboard.

Conclusion

Subclass a UIHostingController have a limitation, we can’t inject dependency to the destination view since it relies on old init?(coder aDecoder: NSCoder). I hope this technique will belong in your toolbox and can help you when the time comes.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

References

Related Post