我们有时可能会需要改变navigationBar的背景颜色。
- 通过appearance改变
UINavigationBar.appearance().backgroundColor = UIColor(red: 64/225, green: 161/225, blue: 64/225, alpha: 1)
- 通过NavigationConfigurator改变
struct NavigationConfigurator: UIViewControllerRepresentable { var configure: (UINavigationController) -> Void = { _ in } func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfigurator>) -> UIViewController { UIViewController() } func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfigurator>) { if let nc = uiViewController.navigationController { self.configure(nc) } } } struct SampleView: View { var body: some View { NavigationView { ZStack { Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) }.navigationBarItems( leading: Button(action: /*@START_MENU_TOKEN@*/ { }/*@END_MENU_TOKEN@*/) { HStack { Image(systemName: "arrow.left") Text("back") }.foregroundColor(broadCastViewHeaderFontColor) }, trailing: Button(action: /*@START_MENU_TOKEN@*/ { }/*@END_MENU_TOKEN@*/) { Text("next").foregroundColor(broadCastViewHeaderFontColor) } ).navigationBarTitle("title", displayMode: .inline).background(NavigationConfigurator { nc in nc.navigationBar.backgroundColor = UIColor(red: 64/225, green: 161/225, blue: 64/225, alpha: 1) }) }.navigationViewStyle(StackNavigationViewStyle()) } }
- iOS14 new
toolbar
NavigationView { Text("My View!") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .principal) { HStack { Image(systemName: "sun.min.fill") Text("Title") .font(.headline) .foregroundColor(.orange) } } } }