You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中使用ForEach循环生成Toolbar按钮不生效问题求解

问题原因

你的写法将ForEach放在了单个ToolbarItem内部,相当于在同一个工具栏项里塞入了多个按钮,受SwiftUI工具栏的布局规则限制,这种写法只会展示首个内容,无法生成多个独立的工具栏按钮。

正确实现

你需要把ForEach移到ToolbarItem外层,循环生成独立的ToolbarItem即可,示例代码如下:

let toolbarIcons = ["magnifyingglass", "plus"]

.toolbar {
    ForEach(toolbarIcons, id: \.self) { icon in
        ToolbarItem {
            Button {
                // 此处添加对应按钮的点击逻辑
            } label: {
                Image(systemName: icon)
            }
        }
    }
}

补充说明

  • 上述写法直接遍历图标字符串数组,用id: \.self作为元素唯一标识,不需要手动处理索引,代码更简洁
  • 如果你需要保留索引遍历的写法,调整嵌套层级即可:
let toolbar = ["magnifyingglass", "plus"]

.toolbar {
    ForEach(toolbar.indices, id: \.self) { index in
        ToolbarItem {
            Button {
                // 点击逻辑
            } label: {
                Image(systemName: toolbar[index])
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Nikolass

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 00:06:07