如何在 SwiftUI 和 iOS 14 中向领先的 navigationBarItems 添加徽章?

How can I add a badge to a leading navigationBarItems in SwiftUI and iOS 14?

如何在 SwiftUI 和 iOS 14 中向 navigationBarItems 添加徽章?

我在网上找不到任何东西...

例如,我想在前导 navigationBarItems:

上添加徽章
var body: some View {
    NavigationView {
        ZStack {
            VStack(spacing: 0) {
                Text("Peanut")
                    .padding(-10)
                    .navigationBarTitle(Text("HomeTitle"), displayMode: .inline)
                    .navigationBarItems(leading:
                        HStack {
                            NavigationLink(destination: Notifications()) {
                                Image(systemName: "bell")
                                    .font(.system(size: 20))
                            }.foregroundColor(.white)
                        }, trailing:
                        HStack {
                            NavigationLink(destination: Settings()) {
                                Image(systemName: "gearshape")
                                    .font(.system(size: 20))
                            }.foregroundColor(.white)
                        })
            }
        }
    }
}

您可以创建自定义 Badge 视图:

struct Badge: View {
    let count: Int

    var body: some View {
        ZStack(alignment: .topTrailing) {
            Color.clear
            Text(String(count))
                .font(.system(size: 16))
                .padding(5)
                .background(Color.red)
                .clipShape(Circle())
                // custom positioning in the top-right corner
                .alignmentGuide(.top) { [=10=][.bottom] }
                .alignmentGuide(.trailing) { [=10=][.trailing] - [=10=].width * 0.25 }
        }
    }
}

并将其用作 overlay:

struct ContentView: View {
    var body: some View {
        NavigationView {
            ZStack {
                VStack(spacing: 0) {
                    Text("Peanut")
                        .padding(-10)
                        .navigationBarTitle(Text("HomeTitle"), displayMode: .inline)
                        .navigationBarItems(leading: leadingBarItems)
                }
            }
        }
    }

    var leadingBarItems: some View {
        NavigationLink(destination: Text("Notifications")) {
            Image(systemName: "bell")
                .font(.system(size: 20))
        }
        .foregroundColor(.primary)
        .padding(5)
        .overlay(Badge(count: 3))
    }
}

备注

徽章视图使用对齐指南进行定位。有关更多信息,请参阅: