Home > AI > IOS > SwiftUI >

make your own TabView

MayTabView.swift



import SwiftUI

struct MyTabView: View {
    
    var viewControllers: [UIHostingController<AnyView>]

    init(_ tabs: [Tab]) {
        self.viewControllers = tabs.map {
            let host = UIHostingController(rootView: $0.view)
            host.tabBarItem = $0.barItem
            return host
        }
    }

    var body: some View {
        MyTabBarController(controllers: viewControllers)
            .edgesIgnoringSafeArea(.all)
    }

    
    struct Tab {
        var view: AnyView
        var barItem: UITabBarItem

        init<V: View>(view: V, barItem: UITabBarItem) {
            self.view = AnyView(view)
            self.barItem = barItem
        }
    }
}


MyTabBarController.swift



import Foundation
import SwiftUI

struct MyTabBarController: UIViewControllerRepresentable {
    var controllers: [UIViewController]

    func makeUIViewController(context: Context) -> UITabBarController {
        let tabBarController = UITabBarController()
        tabBarController.viewControllers = controllers
        return tabBarController
    }

    func updateUIViewController(_ uiViewController: UITabBarController, context: Context) {

    }
}

ExampleView.swift


import SwiftUI

struct ExampleView: View {
    @State var text: String = ""

    var body: some View {
        MyTabView([
            MyTabView.Tab(
                view: NavView(),
                barItem: UITabBarItem(title: "First", image: nil, selectedImage: nil)
            ),
            MyTabView.Tab(
                view: Text("Second View"),
                barItem: UITabBarItem(title: "Second", image: nil, selectedImage: nil)
            )
        ])
    }
}

struct NavView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: Text("This page stays when you switch back and forth between tabs (as expected on iOS)")) {
                    Text("Go to detail")
                }
            }
        }
    }
}

struct ExampleView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleView()
    }
}

Leave a Reply