Is there any way to use storyboard and SwiftUI in same iOS Xcode project?
I just started to look at the SwiftUI
. Sharing a small example.
- In the
storyboard
addHosting View Controller
- Subclass the
UIHostingController
with your own class (ChildHostingController
) ChildHostingController
should look something like that:
import UIKitimport SwiftUIstruct SecondView: View { var body: some View { VStack { Text("Second View").font(.system(size: 36)) Text("Loaded by SecondView").font(.system(size: 14)) } }}class ChildHostingController: UIHostingController<SecondView> { required init?(coder: NSCoder) { super.init(coder: coder,rootView: SecondView()); } override func viewDidLoad() { super.viewDidLoad() }}
For more details have a look at Custom UIHostingController
Apple Docs UIhostingController (Unfortunatelly it hasn't been documented yet)
Integrating SwiftUI Video
Yes you can do that! Here are the steps you can take to do so:
Go to your current Xcode project -> Storyboard, click on the + sign (right upper corner) and search for Hosting Controller (just like you would for a button or label).
Drag Hosting Controller to your Storyboard. Create a Segue connection from your UI element (I'm using a button) to that Hosting Controller and select Push.Create an outlet connection from that Segue to your View Controller (it's a new feature - just like you would create an outlet for a Label), and name it.
- Declare your view inside of this outlet connection (you can do that, don't have to use PrepareForSegue method), and return it.
For example: I created a SwiftUI view in my current project (in Xcode: File -> New -> File -> SwiftUI View) and called it DetailsView. My outlet connection would look like this:
import UIKit import SwiftUIclass ViewController: UIViewController { @IBSegueAction func showDetails(_ coder: NSCoder) -> UIViewController? { let detailsView = DetailsView() return UIHostingController(coder: coder, rootView: detailsView) } override func viewDidLoad() { super.viewDidLoad() // some code }}
That's it! Now run it.
as Edgell Mentioned, there is a new ViewController
named HostViewController
that can host a SwiftUI
page inside it.there's a complete talk about integrating SwiftUI in existing project at WWDC that answers your question very well.
Integrating SwiftUI:https://developer.apple.com/videos/play/wwdc2019/231/