gpt4 book ai didi

swift - 如何避免 SwiftUI 中的嵌套导航栏?

转载 作者:可可西里 更新时间:2023-11-01 01:47:06 25 4
gpt4 key购买 nike

我使用 SwiftUI 构建了一个 NavigationView,它将用户带到另一个 NavigationView,最后带到一个简单的 View。当我到达最后一个 View 时,我可以看到两个后退按钮和一个非常大的导航栏。

GIF showing nested navigation bars

我想要一个类似于 iOS 设置应用的导航结构,其中一个导航列表转到另一个导航列表,每个导航列表都有一个返回上一屏幕的后退按钮。

有人知道怎么解决吗?

最佳答案

您的 View 层次结构中应该只有一个 NavigationView,作为菜单 View 的祖先。然后,您可以在该层次结构的任何级别使用 NavigationLink

因此,例如,您的 Root View 可以这样定义:

struct RootView: View {
var body: some View {
NavigationView {
MenuView()
.navigationBarItems(trailing: profileButton)
}
}

private var profileButton: some View {
Button(action: { }) {
Image(systemName: "person.crop.circle")
}
}
}

然后您的菜单 View 具有指向适当 View 的 NavigationLink:

struct MenuView: View {
var body: some View {
List {
link(icon: "calendar", label: "Appointments", destination: AppointmentListView())
link(icon: "list.bullet", label: "Work Order List", destination: WorkOrderListView())
link(icon: "rectangle.stack.person.crop", label: "Contacts", destination: ContactListView())
link(icon: "calendar", label: "My Calendar", destination: MyCalendarView())
}.navigationBarTitle(Text("Menu"), displayMode: .large)
}

private func link<Destination: View>(icon: String, label: String, destination: Destination) -> some View {
return NavigationLink(destination: destination) {
HStack {
Image(systemName: icon)
Text(label)
}
}
}
}

您的约会 ListView 还包含指向约会详细信息 View 的 NavigationLink:

struct AppointmentListView: View {
var body: some View {
List {
link(destination: AppointmentDetailView())
link(destination: AppointmentDetailView())
link(destination: AppointmentDetailView())
}.navigationBarTitle("Appointments")
}

private func link<Destination: View>(destination: Destination) -> some View {
NavigationLink(destination: destination) {
AppointmentView()
}
}
}

结果:

demo

关于swift - 如何避免 SwiftUI 中的嵌套导航栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com