はじめに
Toolbarを関数に切り出す時にsome View
だとできなかったのでやり方を調べました
他のViewとは違うやり方だったので記録しておきます。
実装
基本形
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationStack {
List {
// cell
}
.toolbar(content: toolbar)
}
}
private func toolbar() -> some ToolbarContent {
ToolbarItem(placement: .navigationBarLeading) {
Button {
// action
} label: {
Text("キャンセル")
}
}
}
}
複数ボタンを配置したい
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationStack {
List {
// cell
}
.toolbar(content: toolbar)
}
}
@ToolbarContentBuilder
private func toolbar() -> some ToolbarContent {
ToolbarItem(placement: .navigationBarLeading) {
Button {
// action
} label: {
Text("キャンセル")
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button {
// action
} label: {
Text("保存")
}
}
}
}
if文で分岐させたい
import SwiftUI
struct ContentView: View {
@State private var isCancel = true
var body: some View {
NavigationStack {
List {
// cell
}
.toolbar(content: toolbar)
}
}
@ToolbarContentBuilder
private func toolbar() -> some ToolbarContent {
if isCancel {
ToolbarItem(placement: .navigationBarLeading) {
Button {
// action
} label: {
Text("キャンセル")
}
}
} else {
ToolbarItem(placement: .navigationBarLeading) {
Button {
// action
} label: {
Text("戻る")
}
}
}
}
}
おわり
これは知りませんでした