简体   繁体   中英

How to add badges to bottom bar buttons in SwiftUI?

I have a bottom bar with buttons in it. I'm having trouble adding badges to the buttons and tried using the native .badges modifier but had no effect.

This is what I'm trying:

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")
                        }
                    }
                }
            }
        }
    }
}

This is what it looks like:

在此处输入图像描述

Is there a way to achieve this in SwiftUI?

Documentation of badge modifier states "Badges are only displayed in list rows and iOS tab bars" . Toolbar is not a Tabbar.

A possible approach is to do that in custom way (because toolbar accepts just a view), so it could be like

演示

Tested with 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
)

Test code on GitHub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM