As Swift 5 introduces the SwiftUI framework for creating the views, but we are currently using the storyboard for UI design.
So I just wanted to know the procedure to use Storyboard and Swift UI in same iOS Single View Application.
No matter what the case is, it's really easy to bring SwiftUI to storyboard based apps and enjoy the benefits it has to offer. This can be done in two ways; either to embed SwiftUI views as NSViews, or as view controllers.
This SwiftUI UIKit integration solution can provide the experience of using SwiftUI without creating a new app from scratch. Adding SwiftUI to an existing UIKit project will also make it easier for us to migrate the app to SwiftUI in the future.
There is no direct way of migrating from storyboard to swift UI. This compels a developer to continue the use of the storyboard for existing apps and in lower versions. Since, it is very new so there is less community support which is not the case for storyboard.
I just started to look at the SwiftUI
. Sharing a small example.
storyboard
add Hosting View Controller
UIHostingController
with your own class (ChildHostingController
) ChildHostingController
should look something like that: import UIKit import SwiftUI struct 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.
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 SwiftUI class 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With