如何在 SwiftUI 中自定义 NavigationLink Accessory-View

解决方案:就是利用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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容