Home > AI > IOS > SwiftUI >

Customized navigation titleView




import SwiftUI

extension View {
    func titleView<V: View>(_ displayMode: NavigationBarItem.TitleDisplayMode = .automatic, @ViewBuilder view: () -> V) -> some View {
        background(NavigationTitleView(displayMode: displayMode, titleView: view()))
    }
}



final class NavigationTitleView<V: View>: UIViewController {
    
    var displayMode: NavigationBarItem.TitleDisplayMode
    var titleView: V
    
    init(displayMode: NavigationBarItem.TitleDisplayMode, titleView: V) {
        self.displayMode = displayMode
        self.titleView = titleView
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func willMove(toParent parent: UIViewController?) {
        super.willMove(toParent: parent)
        
        switch displayMode {
        case .automatic:
            parent?.navigationItem.largeTitleDisplayMode = .automatic
        case .inline:
            parent?.navigationItem.largeTitleDisplayMode = .never
        case .large:
            parent?.navigationItem.largeTitleDisplayMode = .always
        @unknown default:
            parent?.navigationItem.largeTitleDisplayMode = .automatic
        }
        guard let uiView = UIHostingController(rootView: titleView).view else {
            fatalError()
        }
        uiView.backgroundColor = .red
        parent?.navigationItem.titleView = uiView
    }
}


extension NavigationTitleView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> some UIViewController {
        self
    }
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        
    }
}



import SwiftUI

struct ListenView: View {
    @EnvironmentObject var home: HomeGlobal
    
    var body: some View {
        NavigationView {
            List {
                NavigationLink(destination: Text("QuestionListView")) {
                    Text("ggg")
                }
                NavigationLink(destination: Text("QuestionListView")) {
                    Text("ggg")
                }
                NavigationLink(destination: Text("QuestionListView")) {
                    Text("ggg")
                }
                NavigationLink(destination: Text("QuestionListView")) {
                    Text("ggg")
                }
            }
            .titleView{
                Text("ggg")
            }
            .navigationBarTitle("", displayMode: .inline)
            .navigationBarHidden(self.home.hiddenBar)
        }
        .onAppear {
            self.home.hiddenBar = false
        }
    }
}

Leave a Reply