値を受け渡して画面遷移する際、最初の挙動でボタンの処理が反映されない

前提

SwiftUIを使って簡単なじゃんけんアプリを作っています。
画面遷移をした際に意図しない挙動が起きています。

実現したいこと

押したボタンによってじゃんけんの手を引き継ぎ、遷移先の画面で自分の手とランダムに決めた相手の手を表示します。

発生している問題・エラーメッセージ

アプリを起動して最初にボタンを押した時に限り、ボタンの処理で入れている値ではなく、初期値が反映される。

該当のソースコード

SwiftUI

//遷移前の画面 import SwiftUI struct ContentView: View { let opposeJankenHands = ["hand.thumbsup", "hand.point.up", "hand.raised"] @State var myJankenHands = "" @State var isShowSecondView = false var body: some View { let bounds = UIScreen.main.bounds let width = CGFloat(bounds.width) let height = CGFloat(bounds.height) VStack{ Button(action: { isShowSecondView = true myJankenHands = "hand.thumbsup" }){ Image(systemName: "hand.thumbsup") .resizable() .scaledToFit() .frame(width: UIScreen.main.bounds.width/5) .padding() .sheet(isPresented: $isShowSecondView){ SecondView(isShowSecondView: $isShowSecondView, myJankenHands: myJankenHands) } } HStack{ Button(action: { isShowSecondView = true myJankenHands = "hand.point.up" }){ Image(systemName: "hand.point.up") .resizable() .scaledToFit() .frame(width: UIScreen.main.bounds.width/5) .padding() .sheet(isPresented: $isShowSecondView){ SecondView(isShowSecondView: $isShowSecondView, myJankenHands: myJankenHands) } } Button(action: { isShowSecondView = true myJankenHands = "hand.raised" }){ Image(systemName: "hand.raised") .resizable() .scaledToFit() .frame(width: UIScreen.main.bounds.width/5) .padding() .sheet(isPresented: $isShowSecondView){ SecondView(isShowSecondView: $isShowSecondView, myJankenHands: myJankenHands) } } } Text("じゃんけんしよう").font(.largeTitle) .padding() .frame(width: width-50, height: width/4) .foregroundColor(.black) } } }

SwiftUI

import SwiftUI //遷移後の画面 struct SecondView: View { @Binding var isShowSecondView:Bool var myJankenHands:String let opposeJankenHands = ["hand.thumbsup", "hand.point.up", "hand.raised"] var body: some View { VStack{ Text("相手の手") .padding(10) Image(systemName: opposeJankenHands.randomElement() ?? "") .resizable() .scaledToFit() .frame(width: UIScreen.main.bounds.width/5) .padding(50) Text("自分の手") .padding(10) Image(systemName: myJankenHands) .resizable() .scaledToFit() .frame(width: UIScreen.main.bounds.width/5) .padding(50) Button(action:{ isShowSecondView = false }){ Text("戻る") .padding() } } } }

試したこと

初期化の処理をinitで別にやってみましたが、意味がありませんでした。

init(){ _myJankenHands = State(initialValue: "") }

コメントを投稿

0 コメント