首页 > 解决方案 > SwiftUI - 视图获取隐藏在导航栏下

问题描述

在我的应用程序中,我想隐藏 UINavigationBar 的底线。为此,我使用 UINavigationBar 的外观()访问器。像这样:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    let contentView = ContentView()

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)
        self.window = window
        window.makeKeyAndVisible()
        
        UINavigationBar.appearance().isTranslucent = false
        UINavigationBar.appearance().shadowImage = UIImage()
        UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
        UINavigationBar.appearance().barTintColor = .white
    }
}

但是当我这样做时,从主视图推送的视图内容会被导航栏重叠。出于某种原因,当我设置isTranslucenttrue推送视图时正常工作,但在这种情况下,导航栏完全是半透明的,并且滚动上的任何内容在它后面都是可见的,我不希望这种行为。

这是我的观点的代码:

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(
                    destination: AnotherView(),
                    label: {
                        Text("Screen 1")
                    })
                Spacer()
            }
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}

struct AnotherView: View {
    var body: some View {
        VStack {
            Text("Screen 2")
            Spacer()
        }
    }
}

如何保持导航栏完全不透明且没有底线并使推送视图正常工作?

重叠

标签: iosswiftxcodeswiftui

解决方案


感谢Asperi ,我在这里遵循了接受的答案

所以我最终通过background修饰符修改了导航栏。我现在拥有的代码:

struct NavigationConfiguration: UIViewControllerRepresentable {
    
init() {
        let navBarAppearance = UINavigationBarAppearance()
        navBarAppearance.configureWithOpaqueBackground()
        navBarAppearance.shadowColor = .clear
        navBarAppearance.backgroundColor = .white
        UINavigationBar.appearance().standardAppearance = navBarAppearance
    }
    
func makeUIViewController(
        context: UIViewControllerRepresentableContext<NavigationConfiguration>
    ) -> UIViewController {
        UIViewController()
    }
    
func updateUIViewController(_ uiViewController: UIViewController,
                                context: UIViewControllerRepresentableContext<NavigationConfiguration>) {}
    
}

在我看来:

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(
                    destination: AnotherView(),
                    label: {
                        Text("Screen 1")
                    })
                Spacer()
            }
            .navigationBarTitleDisplayMode(.inline)
            .background(NavigationConfiguration())
        }
    }
}

推荐阅读