当您单击该按钮时,它会将您带到一个新视图,并在左上角放置一个后退按钮。我不知道什么属性控制后退按钮的颜色。我尝试添加accentColor和foregroundColor,但它们只编辑视图内的项目。
var body: some View {
NavigationView {
NavigationLink(destination: ResetPasswordView()) {
Text("Reset Password")
.foregroundColor(Color(red: 0, green: 116 / 255, blue: 217 / 255))
.padding()
}
}
}
您可以使用NavigationView上的
accentColor
属性来设置后退按钮颜色,如下例所示:
var body: some View {
NavigationView {
List(1..<13) { item in
NavigationLink(destination: Text("\(item) x 8 = \(item*8)")) {
Text(String(item))
}
}.navigationBarTitle("Table of 8")
}.accentColor(.black) // <- note that it's added here and not on the List like navigationBarTitle()
}
我尝试做同样的事情有一段时间了,但认为还没有 SwiftUI 解决方案。不过,能够完成工作的一件事(如果它适用于您的用例)是 UIKit 的外观:
UINavigationBar.appearance().tintColor = .black
我怀疑这是正确的方法,但我通过修改 SceneDelegate.swift 来设置窗口色调颜色来使其工作。
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use a UIHostingController as window root view controller
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: ContentView())
window.tintColor = .green // set the colour of the back navigation text
self.window = window
window.makeKeyAndVisible()
}
NavigationView {
Text("Hello World")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Close") { }
}
}
}
.accentColor(.themeColor)
Assets.xcassets
中设置 AccentColor。 XCode 将为应用程序中的所有导航后退按钮使用此颜色。
请注意,这也会影响其他 UI 元素。其中之一是按钮。您始终可以使用accentColor修饰符来覆盖它:Button("Button With Different Accent Color") {
// do something useful
}
.accentColor(.red)
。 Xcode 应用您在此颜色集中指定的颜色作为应用程序的强调色。 简短的解决方案
更多详情
在项目导航器中,选择资产目录。
SwiftUI
Text("Accent Color")
.foregroundStyle(Color.accentColor)
UIKit
label.textColor = UIColor.tintColor
什么是强调色?
import Foundation
import SwiftUI
struct NavigationBackButton: ViewModifier {
@Environment(\.presentationMode) var presentationMode
var color: UIColor
var text: String?
func body(content: Content) -> some View {
return content
.navigationBarBackButtonHidden(true)
.navigationBarItems(
leading: Button(action: { presentationMode.wrappedValue.dismiss() }, label: {
HStack(spacing: 2) {
Image(systemName: "chevron.backward")
.foregroundColor(Color(color))
if let text = text {
Text(text)
.foregroundColor(Color(color))
}
}
})
)
}
}
extension View {
func navigationBackButton(color: UIColor, text: String? = nil) -> some View {
modifier(NavigationBackButton(color: color, text: text))
}
}
使用方法非常简单,只需在导航链接的目标视图上使用此修饰符即可。
带有文字的后退按钮:
.navigationBackButton(color: .white, text: "Back")
无文字的后退按钮:
.navigationBackButton(color: .white)
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.backButtonAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.white]
iOS 16
中,
.accentColor
被标记为已弃用。请使用 .tint
来代替。NavigationStack {
List {
NavigationLink("Action_1") {
Action_1_View()
}
NavigationLink("Action_2") {
Action_2_View()
}
}
}
.tint(.gray)