简体   繁体   English

如何在 SwiftUI 的底部栏按钮上添加徽章?

[英]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.我在向按钮添加徽章时遇到问题,并尝试使用本机.badges修饰符,但没有效果。

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?有没有办法在 SwiftUI 中实现这一点?

Documentation of badge modifier states "Badges are only displayed in list rows and iOS tab bars" .徽章修饰符的文档指出“徽章仅显示在列表行和 iOS 选项卡栏中”。 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使用 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 GitHub上的测试代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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