我想知道是否有办法在 SwiftUI 中制作持久工具栏?我发现了一些人们制作具有动态元素的工具栏的示例,但我还没有找到跨多个页面/视图持久存在的工具栏的良好解决方案。
显然,我可以选择为每个 NavigationView 页面复制/粘贴所有“.toolbar”代码,但这似乎有点低效。
想法?
附注有没有办法给工具栏添加阴影?网上没找到有用的东西...
我目前有以下代码:
.toolbar
{
ToolbarItem (placement: .principal) {
PersistentToolbar()
}
}
/*
----------------------------------------------------------
Where PersistentToolbar() is defined (in another file) as:
----------------------------------------------------------
*/
struct PersistentToolbar: View {
var body: some View {
HStack {
Image(systemName: "line.3.horizontal")
.foregroundColor(.black)
Spacer()
Button(action: {
print("Go Home")
}, label: {
Image("Logo")
.resizable()
.frame(width: 40, height: 40)
})
Spacer()
Button {
print("Profile Page")
} label: {
NavigationLink(destination: ProfileView()) { // I want to navigate to a "ProfilePage" when the user taps the profile icon
Image(systemName: "person.crop.circle")
}
.foregroundColor(.black)
}
}
}
}
定义一个“包装视图”,将工具栏添加到每个“包装视图”
struct WrappedToolbarView <Root> : View where Root : View {
var root: () -> Root
var body: some View {
root()
.toolbar {
ToolbarItem (placement: .principal) {
PersistentToolbar()
}
}
}
}
现在,每当您导航到另一个视图(通过
NavigationLink
或 .navigationDestination
)时,您都可以使用 WrappedToolbarView
。
struct DetailView: View {
var body: some View {
WrappedToolbarView {
Text ("some details")
}
}
}