我正在尝试为导航 .toolbarBackground 设置自定义渐变,但任何时候我都只使用 LinearGradient 中的第一种颜色运行它。
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Menu {
// MARK: 2 Actions
// 1. logout
// 2. Delete Account
Button("Logout",action: logOutUser)
Button("Delete Account",role: .destructive,action: deleteAccount)
} label: {
Image(systemName: "slider.horizontal.3")
.rotationEffect(.init(degrees: 90))
.tint(.white)
.scaleEffect(0.8)
}
}
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle("My Garden")
.toolbarColorScheme(.dark, for: .navigationBar)
.toolbarBackground(.visible, for: .navigationBar)
.toolbarBackground(LinearGradient(gradient: Gradient(colors: [Color("Green1"), Color("Green2")]),startPoint: .bottomLeading,endPoint: .topTrailing))
我最近遇到了同样的问题,根据 Sarunw 的博客文章,从 iOS 16 开始这是不可能的:
在当前的测试版中,我们无法使用其他ShapeStyle
like
LinearGradient
.
我已经提交了错误报告,一旦我知道它是错误的,我就会更新该帖子
预期的行为或错误。
→ https://sarunw.com/posts/swiftui-navigation-bar-color/#basic-usage https://sarunw.com/posts/swiftui-navigation-bar-color/#basic-usage
替代解决方案
如果你不想等待 iOS 17maybe解决这个问题,你可以回退到 UIKit 并使用UINavigationBarAppearance
相反并使用渐变图像。我想你甚至可以在代码中创建渐变图像,但我只是最终将渐变图像放入资产目录中(默认,不切片)并将其提供给导航栏,如下所示backgroundImage
.
有很多教程展示了这种方式,例如this https://khorbushko.github.io/article/2020/11/24/navigation-bar.html, this https://schwiftyui.com/swiftui/customizing-your-navigationviews-bar-in-swiftui/ or 这个视频 https://www.youtube.com/watch?v=kCJyhG8zjvY。最后他们都得到了某种形式的代码:
struct MainNavigationBar: ViewModifier {
init() {
let appearance = UINavigationBarAppearance()
// Custom gradient background
appearance.backgroundImage = UIImage(named: "NavigationBarBackground")
// Apply custom styling to all bar states
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
UINavigationBar.appearance().compactAppearance = appearance
// Custom button color tinting
// (buggy and not working for me for some reason)
UINavigationBar.appearance().tintColor = .white
}
func body(content: Content) -> some View {
content
}
}
现在您可以在NavigationStack
将此样式附加到视图和所有子视图。
NavigationStack {
// Your Content
}
.modifier(MainNavigationBar())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)