Cod*_*der 2 ios ios13 swiftui ios-navigationview uiviewcontrollerrepresentable
我正在使用一个基于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()
}
}
Run Code Online (Sandbox Code Playgroud)
以纵向模式启动应用程序时的显示方式:
...并旋转为横向...
最后,以横向模式启动时的外观。
我还注销了NavigationConfigurator,发现当它以纵向模式启动时,有两个电话。第一个无法找到导航控制器,但第二个可以找到。
当我以横向模式启动时,仅进行了一次调用,但无法找到它。旋转后,它会找到它并成功更新颜色。
我确实尝试通过@State管理强制重画,但没有成功。
由于无法将应用程序锁定为纵向模式,我已经没有主意了。
如果它只是关于条形色调颜色并且不需要更多的导航控制器,那么使用外观会更简单,因为
struct ContentView: View {
init() {
UINavigationBar.appearance().barTintColor = UIColor.orange
}
// .. your other code here
Run Code Online (Sandbox Code Playgroud)
该解决方案适用于任何初始方向。使用 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>) {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2337 次 |
| 最近记录: |