前提
SwiftUIを使って簡単なじゃんけんアプリを作っています。
画面遷移をした際に意図しない挙動が起きています。
実現したいこと
押したボタンによってじゃんけんの手を引き継ぎ、遷移先の画面で自分の手とランダムに決めた相手の手を表示します。
- 押したボタンでじゃんけんの出す手を決める
- 画面遷移して、遷移した画面で自分の手とランダムに決めた相手の手を表示する
発生している問題・エラーメッセージ
アプリを起動して最初にボタンを押した時に限り、ボタンの処理で入れている値ではなく、初期値が反映される。
該当のソースコード
SwiftUI
1//遷移前の画面 2import SwiftUI 3 4struct ContentView: View { 5 let opposeJankenHands = ["hand.thumbsup", "hand.point.up", "hand.raised"] 6 @State var myJankenHands = "" 7 @State var isShowSecondView = false 8 9 var body: some View { 10 11 let bounds = UIScreen.main.bounds 12 let width = CGFloat(bounds.width) 13 let height = CGFloat(bounds.height) 14 15 VStack{ 16 Button(action: { 17 isShowSecondView = true 18 myJankenHands = "hand.thumbsup" 19 }){ 20 Image(systemName: "hand.thumbsup") 21 .resizable() 22 .scaledToFit() 23 .frame(width: UIScreen.main.bounds.width/5) 24 .padding() 25 26 .sheet(isPresented: $isShowSecondView){ 27 SecondView(isShowSecondView: $isShowSecondView, myJankenHands: myJankenHands) 28 } 29 } 30 31 HStack{ 32 Button(action: { 33 isShowSecondView = true 34 myJankenHands = "hand.point.up" 35 }){ 36 Image(systemName: "hand.point.up") 37 .resizable() 38 .scaledToFit() 39 .frame(width: UIScreen.main.bounds.width/5) 40 .padding() 41 42 .sheet(isPresented: $isShowSecondView){ 43 SecondView(isShowSecondView: $isShowSecondView, myJankenHands: myJankenHands) 44 } 45 } 46 47 Button(action: { 48 isShowSecondView = true 49 myJankenHands = "hand.raised" 50 51 }){ 52 Image(systemName: "hand.raised") 53 .resizable() 54 .scaledToFit() 55 .frame(width: UIScreen.main.bounds.width/5) 56 .padding() 57 58 .sheet(isPresented: $isShowSecondView){ 59 SecondView(isShowSecondView: $isShowSecondView, myJankenHands: myJankenHands) 60 } 61 } 62 } 63 Text("じゃんけんしよう").font(.largeTitle) 64 .padding() 65 .frame(width: width-50, height: width/4) 66 .foregroundColor(.black) 67 68 } 69 } 70}
SwiftUI
1import SwiftUI 2//遷移後の画面 3struct SecondView: View { 4 @Binding var isShowSecondView:Bool 5 var myJankenHands:String 6 let opposeJankenHands = ["hand.thumbsup", "hand.point.up", "hand.raised"] 7 8 var body: some View { 9 VStack{ 10 Text("相手の手") 11 .padding(10) 12 Image(systemName: opposeJankenHands.randomElement() ?? "") 13 .resizable() 14 .scaledToFit() 15 .frame(width: UIScreen.main.bounds.width/5) 16 .padding(50) 17 Text("自分の手") 18 .padding(10) 19 Image(systemName: myJankenHands) 20 .resizable() 21 .scaledToFit() 22 .frame(width: UIScreen.main.bounds.width/5) 23 .padding(50) 24 Button(action:{ 25 isShowSecondView = false 26 }){ 27 Text("戻る") 28 .padding() 29 } 30 } 31 } 32}
試したこと
初期化の処理をinitで別にやってみましたが、意味がありませんでした。
init(){ _myJankenHands = State(initialValue: "") }

回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2022/12/12 05:16