Noah Iarrobino
Noah Iarrobino

Reputation: 1543

How do I add a SwiftUI view to an existing Tab Bar Controller

I have an app that uses storyboard, I need one of the tabs to be SwiftUI, how can I add it to my existing project?

Upvotes: 1

Views: 1424

Answers (1)

Noah Iarrobino
Noah Iarrobino

Reputation: 1543

I assume someone will need to know this at some point,

step 1. Add a Hosting View Controller to your storyboard

step 2. Create a root view controller relationship segue between your navigation controller/tab bar controller and the HostingView Controller

step 3. create your SwiftUI Class

import SwiftUI

struct AnalyticsView: View {
    var body: some View {
        Text("Hello")
    }
    
}

struct AnalyticsView_Previews: PreviewProvider {
    static var previews: some View {
        ("Hello World")
    }
}

step 4. create a UIHostingController class and set the HostingViewController to that class in the class inspector

import UIKit
import SwiftUI

class AnalyticsVC: UIHostingController<AnalyticsView> {

    required init?(coder aDecoder: NSCoder){
        super.init(coder: aDecoder, rootView: AnalyticsView())
    }
}

step 5. build your view controller from your SwiftUI view

Upvotes: 1

Related Questions