如何使用 SwiftUI 的 ToolbarItemGroup? [英] How does one use SwiftUI's ToolbarItemGroup?
问题描述
我显然不明白 SwiftUI 定义语法的含义,因为我不知道如何使用 ToolbarItemGroup.
I clear don't understand the meaning of the definition syntax for SwiftUI because I can't figure out how one would use ToolbarItemGroup.
我可以用这样的工具栏项目定义一个工具栏:
I can define a toolbar with toolbar items like this:
.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)
}
}
但是一直无法让 ToolbarItemGroup 工作.从逻辑上讲,我会期待这样的事情:
But have been unable to get ToolbarItemGroup to work. Logically I would have expected something like this:
.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)
}
}
}
推荐答案
ToolbarItemGroup
是输出实体,而不是输入 - 从以下 toolbar
构建器中可以清楚地看出:
The ToolbarItemGroup
is output entity, not input - as it is clear from the following toolbar
builders:
/// 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
因此,.toolbar
会根据工具栏项目的位置(按预定义的顺序)自动生成组.
Thus groups are generated automatically by .toolbar
based on toolbar items placement (in predefined order).
这是示例(使用 Xcode 12b/iOS 14 测试)
Here is example (tested with 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") }
}
}
这篇关于如何使用 SwiftUI 的 ToolbarItemGroup?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!