gpt4 book ai didi

ios - 当我的基于 SwiftUI 的应用程序以横向模式启动时,导航栏上的背景颜色未设置

转载 作者:行者123 更新时间:2023-12-01 15:57:03 26 4
gpt4 key购买 nike

我正在使用一个基于 SwiftUI 的应用,该应用依赖 NavigationView 从屏幕进行转换。

我需要在导航栏上设置背景颜色,并且找到了大部分时间都可以实现此功能的代码。

当应用程序以纵向模式启动时,所有旋转都可以正常工作。

但是,当应用程序以横向模式启动时,该栏为默认灰色,并且仅在第一次旋转后更新。

下面,我用最少的代码来重现我的问题:

import SwiftUI

struct ContentView: View {
var body: some View {
return NavigationView {
List {
NavigationLink(destination: Text("A")) {
Text("See A")
}
}
.background(NavigationConfigurator { navigationConfigurator in
navigationConfigurator.navigationBar.barTintColor = .orange
})
.navigationBarTitle(Text(verbatim: "Home"), displayMode: .inline)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}

struct NavigationConfigurator: UIViewControllerRepresentable {
var configure: (UINavigationController) -> Void = { _ in }

func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfigurator>) -> UIViewController {
UIViewController()
}

func updateUIViewController(_ uiViewController: UIViewController,
context: UIViewControllerRepresentableContext<NavigationConfigurator>) {
if let navigationController = uiViewController.navigationController {
self.configure(navigationController)
print("Successfully obtained navigation controller")
} else {
print("Failed to obtain navigation controller")
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

以纵向模式启动应用程序时的显示方式:

enter image description here

...并旋转为横向...

enter image description here

最后,以横向模式启动时的外观。

enter image description here

我还注销了 NavigationConfigurator 并发现当它以纵向模式启动时,会进行两次调用。第一个无法找到导航 Controller ,但第二个可以找到。

当我以横向模式启动时,仅进行了一次调用,但无法找到它。旋转后,它会找到它并成功更新颜色。

我确实尝试通过 @State 管理强制重绘,但没有成功。

由于无法将应用程序锁定为纵向模式,我已经没有主意了。

最佳答案

如果它只是关于条形色调颜色并且不需要更多的导航 Controller ,那么使用外观会更简单,因为

struct ContentView: View {
init() {
UINavigationBar.appearance().barTintColor = UIColor.orange
}
// .. your other code here

该解决方案适用于任何初始方向。使用 Xcode 11.4 进行测试。

替代:

如果您仍然想通过配置器访问,根据我的经验,以下解决方案(经过测试和工作)更可靠

struct NavigationConfigurator: UIViewControllerRepresentable {
var configure: (UINavigationController) -> Void = { _ in }

func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfigurator>) -> UIViewController {
let controller = UIViewController()
DispatchQueue.main.async {
if let navigationController = controller.navigationController {
self.configure(navigationController)
print("Successfully obtained navigation controller")
} else {
print("Failed to obtain navigation controller")
}
}
return controller
}

func updateUIViewController(_ uiViewController: UIViewController,
context: UIViewControllerRepresentableContext<NavigationConfigurator>) {
}
}

关于ios - 当我的基于 SwiftUI 的应用程序以横向模式启动时,导航栏上的背景颜色未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61409972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com