An alternative question title could be "How to add an UIHostingController's view as subview for an UIView?".
I am creating a new piece of UI component and would love to give SwiftUI a try. The image below is the current view structure. The UIView is what I am using right now (top right), and SwiftUI view is what I try to use (bottom right).
After I watched all SwiftUI videos from WWDC 2019. I still have no clue on how can I use a SwiftUI view and put it at where a UIView instance should go.
I noticed from "Integrating SwiftUI" talk is that there is an NSHostingView
for macOS, https://developer.apple.com/documentation/swiftui/nshostingview# which made me wonder if there is something similar to it or what is the alternative to achieve it.
I read questions like Include SwiftUI views in existing UIKit application mentioned that SwiftUI and UIKit can play together with UIHostingController
. However, what I am trying to do is to only adopt one small piece of SwiftUI and put it inside of my existing UIKit view component, not use it as a controller.
I am new to iOS development, please leave a comment if there is a way I can use view controller as UIView view. Thank you.
View controllers are not just for the top level scene. We often place view controllers within view controllers. It’s called “view controller containment” and/or “child view controllers”. (BTW, view controller containers are, in general, a great way to fight view controller bloat in traditional UIKit apps, breaking complicated scenes into multiple view controllers.)
So,
Go ahead and use
UIHostingController
:and;
Add the view controller can then add the hosting controller as a child view controller:
Obviously, you’d also set the
frame
or the layout constraints for the hosting controller’sview
.See the Implementing a Container View Controller section of the
UIViewController
documentation for general information about embedding one view controller within another.For example, let’s imagine that we had a SwiftUI View to render a circle with text in it:
And let’s say this was our view’s model:
Then our UIKit view controller could add the SwiftUI view, set its frame/constraints within the
UIView
, and update its model as you see fit:I have some idea in mind.
UIHostingController
Thus:
Reference