0

我希望能够在 SwiftUI 中为 NavBar 和 navigationBarItems 设置自定义颜色。这是导航栏项的代码:

.navigationBarItems(leading: EditButton(), trailing: Button(action: {
     self.showingAddScreen.toggle()
 }) {
     Image(systemName: "plus")
 })
 .sheet(isPresented: $showingAddScreen) {
     NavigationView {
         AddTaskView().environment(\.managedObjectContext, self.moc)
     }
}

我使用以下代码创建了一个扩展,它在 NavigationBar 背景颜色上效果很好,但它不会改变 navigationBarItems 的颜色——它们具有默认的蓝色按钮。

extension UINavigationController {
    override open func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let standardAppearance = UINavigationBarAppearance()
        standardAppearance.backgroundColor = UIColor(red: 66/255, green: 116/255, blue: 147/255, alpha: 1.0)

        let scrollEdgeAppearance = UINavigationBarAppearance()
        scrollEdgeAppearance.backgroundColor = UIColor(red: 66/255, green: 116/255, blue: 147/255, alpha: 1.0)

        let compactAppearance = UINavigationBarAppearance()
        compactAppearance.backgroundColor = UIColor(red: 66/255, green: 116/255, blue: 147/255, alpha: 1.0)

        navigationBar.standardAppearance = standardAppearance
        navigationBar.scrollEdgeAppearance = scrollEdgeAppearance
        navigationBar.compactAppearance = compactAppearance

        navigationBar.tintColor = UIColor.white
    }
}

更改 navigationBarItems 颜色的正确方法是什么?

4

1 回答 1

0

我发现虽然通用设置可能很方便,但您实际上可以为每个按钮设置 .foregroundColor 样式:

  .navigationBarItems(leading: EditButton().foregroundColor(Color.white), trailing: Button(action: {
                    self.showingAddScreen.toggle()
                }) {
                    Image(systemName: "plus")
                        .foregroundColor(Color.white)
                })
                .sheet(isPresented: $showingAddScreen) {
                    NavigationView {
                        AddTaskView().environment(\.managedObjectContext, self.moc)
                    }
            }
于 2020-05-11T20:51:41.540 回答