SwiftUI声明工具栏协议ToolbarContent
SwiftUI声明工具栏协议ToolbarContent

SwiftUI声明工具栏协议ToolbarContent

ToolbarContent 是 SwiftUI 中用于声明工具栏内容的协议类型,配合 toolbar 修饰符使用,用来在 macOS、iPadOS 或 iOS 的导航栏、工具栏中添加按钮、菜单等控件。

ToolbarContent 是一个 协议。

在 .toolbar {} 里的内容,其实就是一个遵循 ToolbarContent 的构建块。

它配合 @ToolbarContentBuilder(结果构建器)使用,允许写多个 ToolbarItem,并且支持 placement(放置位置)控制。

基本用法

struct MyToolbar: ToolbarContent {
    var body: some ToolbarContent {
        ToolbarItem(placement: .automatic) {
            Button("刷新") {
                print("刷新按钮点击")
            }
        }
    }
}

struct ContentView: View {
    var body: some View {
        Text("Hello")
            .toolbar {
                MyToolbar() // 提取 ToolbarContent 结构
            }
    }
}

通过ToolbarContent可以将ToolbarItem封装到结构中,在toolbar中使用该结构。

ToolbarContent位置

1、iOS:导航栏(navigation bar)。

2、iPadOS:工具栏(toolbar)。

3、macOS:窗口顶部工具栏(如 Finder 的 toolbar)。

macOS 上如果用 WindowGroup,工具栏会显示在窗口顶端;iOS 上是在 NavigationView 中用 toolbar。

placement 常见值

1、.automatic:自动决定位置(默认)。

2、.navigationBarLeading:导航栏左侧。

3、.navigationBarTrailing:导航栏右侧。

4、.bottomBar:底部工具栏。

5、.primaryAction (macOS):主操作区。

6、.confirmationAction:确认(如“完成”)按钮。

7、.cancellationAction:取消按钮。

注意,macOS和iOS平台支持的placement不同,需要根据平台调整placement值。

总结

ToolbarContent 是在 SwiftUI 中用 .toolbar {} 时背后用的“工具栏内容协议”,它允许声明多个 ToolbarItem,并控制它们在导航栏或工具栏中的位置和表现。

相关文章

1、Swift toolbar工具栏:https://fangjunyu.com/2024/12/07/swift-toolbar%e5%b7%a5%e5%85%b7%e6%a0%8f/

2、SwiftUI设置工具栏背景的toolbarBackground修饰符:https://fangjunyu.com/2024/12/27/swiftui%e8%ae%be%e7%bd%ae%e5%b7%a5%e5%85%b7%e6%a0%8f%e8%83%8c%e6%99%af%e7%9a%84toolbarbackground%e4%bf%ae%e9%a5%b0%e7%ac%a6/

3、SwiftUI导航栏toolbar标题修饰符navigationBarTitleDisplayMode:https://fangjunyu.com/2025/03/05/swiftui%e5%af%bc%e8%88%aa%e6%a0%8ftoolbar%e6%a0%87%e9%a2%98%e4%bf%ae%e9%a5%b0%e7%ac%a6navigationbartitledisplaymode/

   

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开发者。

欢迎加入我们的 微信交流群QQ交流群,交流更多精彩内容!
微信交流群二维码 QQ交流群二维码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注