簡體   English   中英

如何在 SwiftUI 的底部欄按鈕上添加徽章?

[英]How to add badges to bottom bar buttons in SwiftUI?

我有一個底部欄,里面有按鈕。 我在向按鈕添加徽章時遇到問題,並嘗試使用本機.badges修飾符,但沒有效果。

這就是我正在嘗試的:

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Test")
            }
            .padding()
            .toolbar {
                ToolbarItemGroup(placement: .bottomBar) {
                    ControlGroup {
                        Button(action: {}) {
                            Label("Button 1", systemImage: "doc")
                                .badge(1)
                        }
                        Button(action: {}) {
                            Label("Button 2", systemImage: "checkmark")
                        }
                        .badge(2)
                        Button(action: {}) {
                            Label("Button 3", systemImage: "person")
                        }
                    }
                }
            }
        }
    }
}

這是它的樣子:

在此處輸入圖像描述

有沒有辦法在 SwiftUI 中實現這一點?

徽章修飾符的文檔指出“徽章僅顯示在列表行和 iOS 選項卡欄中”。 工具欄不是標簽欄。

一種可能的方法是以自定義方式執行此操作(因為工具欄只接受一個視圖),所以它可能像

演示

使用 Xcode 13.4 / iOS 15.5 測試

ControlGroup {
    Button(action: {}) {
        Label("Button 1", systemImage: "doc")
    }
    Button(action: {}) {
        Label("Button 2", systemImage: "checkmark")
    }
    Button(action: {}) {
        Label("Button 3", systemImage: "person")
    }
}
.overlay(HStack(alignment: .top) {            // << here !!
    Image(systemName: "1").foregroundColor(.green)
        .frame(maxWidth: .infinity)
    Image(systemName: "3").foregroundColor(.orange)
        .frame(maxWidth: .infinity)
    Image(systemName: "9").foregroundColor(.purple)
        .frame(maxWidth: .infinity)
    }
    .frame(maxHeight: .infinity)
    .symbolVariant(.fill)
    .symbolVariant(.circle)
    .allowsHitTesting(false)
    .offset(x: 10, y: -10)
         // ^^^^ just for demo simplicity, can be somehow dynamic
)

GitHub上的測試代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM