SwiftUI Alertを複数使い分けたい
サンプルアプリ
機能
Toggle Switchのある側のAlertを表示します。
Alert複数使い分け
表示されないコード
「Show Alert 2」は表示されます。
「Show Alert 1」は無反応です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import SwiftUI struct ContentView : View { @State var showAlert = false @State var showAlert1 = false @State var showAlert2 = false var body : some View { VStack { HStack { Text ( "Alert 1" ) Toggle ( isOn : $ showAlert ) { EmptyView () } . labelsHidden () Text ( "Alert 2" ) } Button ( action : { if self . showAlert == false { self . showAlert1 . toggle () } else { self . showAlert2 . toggle () } }) { Text ( "Show Alert" ) } . alert ( isPresented : $ showAlert1 ) { Alert ( title : Text ( "Show Alert 1" )) } . alert ( isPresented : $ showAlert2 ) { Alert ( title : Text ( "Show Alert 2" )) } } . padding ( 8.0 ) } } struct ContentView_Previews : PreviewProvider { static var previews : some View { ContentView () } } |
表示されるコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import SwiftUI struct ContentView : View { @State var showAlert = false @State var showAlert1and2 = false var body : some View { VStack { HStack { Text ( "Alert 1" ) Toggle ( isOn : $ showAlert ) { EmptyView () } . labelsHidden () Text ( "Alert 2" ) } Button ( action : { self . showAlert1and2 . toggle () }) { Text ( "Show Alert" ) } . alert ( isPresented : $ showAlert1and2 ) { switch ( showAlert ) { case false : return Alert ( title : Text ( "Show Alert 1" )) case true : return Alert ( title : Text ( "Show Alert 2" )) } } } . padding ( 8.0 ) } } struct ContentView_Previews : PreviewProvider { static var previews : some View { ContentView () } } |
表示されるコード(Toggleがなかった場合)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | import SwiftUI struct ContentView : View { @State var showAlert = false @State var showAlert1and2 = false @State var alert = 1 var body : some View { VStack { HStack { Text ( "Alert 1" ) Toggle ( isOn : $ showAlert ) { EmptyView () } . labelsHidden () Text ( "Alert 2" ) } Button ( action : { switch ( self . showAlert ) { case false : self . alert = 1 case true : self . alert = 2 } self . showAlert1and2 . toggle () }) { Text ( "Show Alert" ) } . alert ( isPresented : $ showAlert1and2 ) { switch ( alert ) { case 1 : return Alert ( title : Text ( "Show Alert 1" )) case 2 : return Alert ( title : Text ( "Show Alert 2" )) default : return Alert ( title : Text ( "Error" )) } } } . padding ( 8.0 ) } } struct ContentView_Previews : PreviewProvider { static var previews : some View { ContentView () } } |