iOS 14
您应该使用toolbar
修饰符:
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Cancel") { /* action */ }
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: { /* Actions */ }, label: {
HStack {
Image(systemName: "trash")
Text("Delete")
}
})
.foregroundColor(.red) // You can apply colors and other modifiers too
}
}

注意 1:您可以在那里拥有ANY View
。(不仅是 a Button
)还有任何修饰符
注意 2:上面和下面的代码都将生成相同的外观项目,但使用不同的方法
iOS 13 及更高版本(已弃用但仍然有效)
你应该使用.navigationBarItems()
修饰符。例如,您可以添加Button
或Image
像这样:
.navigationBarItems(
leading: Button("Cancel") {
// Actions
},
trailing: Button(action: {
// Actions
}, label: { Label("Delete", systemImage: "trash") }
).foregroundColor(.red) // You can apply colors and other modifiers too
)
专家提示
始终尝试将每个项目封装在一个单独的结构中,这样您的代码将被简化并且很容易被更新的技术替换。例如,看一下这个示例:
.navigationBarItems(
leading: MyCustomButtonItem(),
trailing: MyCustomButtonItem(text: "foo", image: "Bard")
)