解決方案:就是利用ZStack,把NavigationLink變成透明層,再覆蓋上原先在label中需要顯示的內容層
// HACK: ZStack with zero opacity + EmptyView
// Hides default chevron accessory view for NavigationLink
ZStack {
NavigationLink {
AboutView()
} label: {
EmptyView()
}
.opacity(0)
Label(title: "About", icon: Image(systemName: "info.circle"))
}
如果不想到處重復的使用這類代碼,我們可以定義一個自己的類
struct BetterNavigationLink<Label: View, Destination: View>: View {
let label: () -> Label
let destination: () -> Destination
init(@ViewBuilder label: @escaping () -> Label,
@ViewBuilder destination: @escaping () -> Destination) {
self.label = label
self.destination = destination
}
var body: some View {
// HACK: ZStack with zero opacity + EmptyView
// Hides default chevron accessory view for NavigationLink
ZStack {
NavigationLink {
self.destination()
} label: {
EmptyView()
}
.opacity(0)
self.label()
}
}
}
使用BetterNavigationLink
代替NavigationLink
即可
BetterNavigationLink {
Label(title: "About", icon: Image(systemName: "info.circle"))
} destination: {
AboutView()
}
參考: How to customize NavigationLink accessory views in SwiftUI