方法
struct sampleView: View {
@State var mode = false
var body: some View {
if mode {
SecondView(mode: $mode)
} else {
FirstView(mode: $mode)
}
}
}
struct FirstView: View {
@Binding var mode: Bool
@State var onAlert = false
var body: some View {
Button(action: {
onAlert = true
}) {
Text("画面遷移")
}
.alert(isPresented: $onAlert, content: {
Alert(title: Text("画面遷移します"), message: Text(""), dismissButton: .default(Text("Ok"), action: {
mode.toggle()
}))
})
}
}
struct SecondView: View {
@Binding var mode: Bool
@State var onAlert = false
var body: some View {
VStack {
Text("サンプル")
Button(action: {
onAlert = true
}) {
Text("画面遷移2")
}
.alert(isPresented: $onAlert, content: {
Alert(title: Text("確認"),
message: Text("画面遷移してもよろしいですか?"),
primaryButton: .cancel(Text("No")),
secondaryButton: .destructive(Text("Ok"), action: {
self.mode.toggle()
}))
})
}
}
}
AlertのButtonには、ボタンをタップしたときの処理をするactionと言うクロージャーがあります。
このクロージャーを使えば、画面遷移をすることができます。
.default(Text(""), action: {
//画面遷移処理
})
最初のコードでは、画面を切り替える変数の値を変えています。
他のアラートのボタン「cancel」、「destructive」でも同じことが出来ます。
まとめ
Alertの画面遷移は、Buttonのactionクロージャーを使う。
おすすめの記事
参考
SwiftUI 徹底入門 | 金田 浩明 |本 | 通販 | Amazon
Amazonで金田 浩明のSwiftUI 徹底入門。アマゾンならポイント還元本が多数。金田 浩明作品ほか、お急ぎ便対象商品は当日お届けも可能。またSwiftUI 徹底入門もアマゾン配送商品なら通常配送無料。
コメント