SwiftUI ナビゲーションバーのタイトルの色を更新する 質問する

SwiftUI ナビゲーションバーのタイトルの色を更新する 質問する

SwiftUIでナビゲーションバーのタイトルの色を変更する方法

NavigationView {
    List {
        ForEach(0..<15) { item in
            HStack {
                Text("Apple")
                    .font(.headline)
                    .fontWeight(.medium)
                    .color(.orange)
                    .lineLimit(1)
                    .multilineTextAlignment(.center)
                    .padding(.leading)
                    .frame(width: 125, height: nil)
                
                Text("Apple Infinite Loop. Address: One Infinite Loop Cupertino, CA 95014 (408) 606-5775 ")
                    .font(.subheadline)
                    .fontWeight(.regular)
                    .multilineTextAlignment(.leading)
                    .lineLimit(nil)
            }
        }
    }
    .navigationBarTitle(Text("TEST")).navigationBarHidden(false).foregroundColor(.orange)
}

試してみました.foregroundColor(.orange)が、うまくいきませんでした

試してみた.navigationBarTitle(Text("TEST").color(.orange))

ベストアンサー1

それはないこれをグローバルに実行するために使用する必要があります.appearance()

SwiftUI はナビゲーション スタイルを直接公開しませんが、 を使用してこれを回避できます。SwiftUI はバックグラウンドでUIViewControllerRepresentable通常の を使用しているため、ビュー コントローラーには有効なプロパティが引き続き存在します。UINavigationController.navigationController

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 ContentView: View {
    var body: some View {
        NavigationView {
            ScrollView {
                Text("Don't use .appearance()!")
            }
            .navigationBarTitle("Try it!", displayMode: .inline)
            .background(NavigationConfigurator { nc in
                nc.navigationBar.barTintColor = .blue
                nc.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
            })
        }
    .navigationViewStyle(StackNavigationViewStyle())
    }
}

ナビゲーションバーの変更

おすすめ記事