我显然不明白 SwiftUI 定义语法的含义,因为我不知道如何使用 ToolbarItemGroup。
我可以定义一个带有工具栏项目的工具栏,如下所示:
.toolbar {
ToolbarItem {
Button("200%", action: zoom200).foregroundColor(controller.scale == 2.0 ? selectedButtonColor : defaultButtonColor)
}
ToolbarItem {
Button("100%", action: zoom100).foregroundColor(controller.scale == 1.0 ? selectedButtonColor : defaultButtonColor)
}
}
Run Code Online (Sandbox Code Playgroud)
但是一直无法让 ToolbarItemGroup 工作。从逻辑上讲,我会期待这样的事情:
.toolbar {
ToolbarItemGroup {
ToolbarItem {
Button("200%", action: zoom200).foregroundColor(controller.scale == 2.0 ? selectedButtonColor : defaultButtonColor)
}
ToolbarItem {
Button("100%", action: zoom100).foregroundColor(controller.scale == 1.0 ? selectedButtonColor : defaultButtonColor)
}
}
ToolbarItemGroup {
ToolbarItem {
Button("Open", action: open)
}
ToolbarItem {
Button("Close", action: close)
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jes*_*ssy 13
ToolbarItemGroup旨在对同一工具栏中的视图进行分组。它消除了明确的使用需要ToolbarItem,既符合ToolbarContent。
例如
.toolbar {
ToolbarItemGroup {
Button("200%", action: zoom200)
.foregroundColor(controller.scale == 2.0 ? selectedButtonColor : defaultButtonColor)
Button("100%", action: zoom100)
.foregroundColor(controller.scale == 1.0 ? selectedButtonColor : defaultButtonColor)
}
ToolbarItemGroup(placement: .bottomBar) {
Spacer()
Button("Open", action: open)
Spacer()
Button("Close", action: close)
Spacer()
}
}
Run Code Online (Sandbox Code Playgroud)
这也是我所知道的Spacer在工具栏项之间使s 工作的唯一方法。
Asp*_*eri 12
这ToolbarItemGroup是输出实体,而不是输入 - 从以下toolbar构建器可以清楚地看出:
/// Populates the toolbar or navigation bar with the specified items.
///
/// - Parameter items: The items representing the content of the toolbar.
public func toolbar<Items>(@ToolbarContentBuilder<Void> items: () -> ToolbarItemGroup<Void, Items>) -> some View
/// Populates the toolbar or navigation bar with the specified items,
/// allowing for user customization.
///
/// - Parameters:
/// - id: A unique identifier for this toolbar.
/// - items: The items representing the content of the toolbar.
public func toolbar<Items>(id: String, @ToolbarContentBuilder<String> items: () -> ToolbarItemGroup<String, Items>) -> some View
Run Code Online (Sandbox Code Playgroud)
因此,组是.toolbar根据工具栏项目的放置(按预定义的顺序)自动生成的。
这是示例(使用 Xcode 12b / iOS 14 测试)
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button(action: {}) { Image(systemName: "book") }
}
ToolbarItem(placement: .primaryAction) {
Button(action: {}) { Image(systemName: "gear") }
}
ToolbarItem(placement: .principal) {
Button(action: {}) { Image(systemName: "car") }
}
ToolbarItem(placement: .principal) {
Button(action: {}) { Image(systemName: "gear") }
}
ToolbarItem(placement: .bottomBar) {
Button(action: {}) { Image(systemName: "1.square") }
}
ToolbarItem(placement: .bottomBar) {
Button(action: {}) { Image(systemName: "2.square") }
}
}
Run Code Online (Sandbox Code Playgroud)