Is there any way to use storyboard and SwiftUI in same iOS Xcode project?

后端 未结 5 1250
有刺的猬
有刺的猬 2020-12-13 06:58

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 t

5条回答
  •  时光取名叫无心
    2020-12-13 07:20

    Yes you can do that! Here are the steps you can take to do so:

    1. 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).

    2. 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.

    1. 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 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.

提交回复
热议问题