関数内で@Binding宣言した変数はどのように初期化すれば良いのか
解決したいこと
関数の中の@Bindingで別のファイルの@State変数を更新したい
発生している問題・エラー
ファイル1で宣言している3つの@State変数を、ファイル2の関数を呼び出したときに@Bindingで更新したい。
ファイル1↓
@State var currentPos:CGPoint = CGPoint(x: 0, y: 0)
@State var deg:Double = 0
@State var imageSize:CGFloat = 60
...
Image(systemName: "***")
.font(.system(size: imageSize))
.position(x: self.currentPos.x, y: self.currentPos.y)
.rotationEffect(Angle(degrees: deg))
...
Button(action: {
processValue.Right.process()
}) {
Text("Right")
}
ファイル2↓
enum processValue {
case Right
case Turn
case Big
func process() {
@Binding var currentPos:CGPoint
@Binding var deg:Double
@Binding var imageSize:CGFloat
switch( self ){
case .Right:
withAnimation(Animation.linear(duration: 0.5)) {
currentPos.x += 80
}
case .Turn:
withAnimation(Animation.linear(duration: 0.5)) {
deg += 90
}
case .Big:
withAnimation(Animation.linear(duration: 0.5)) {
imageSize += 30
}
}
}
}
上の記述をすると、以下のように注意されました。
Variable '_currentPos' captured by a closure before being initialized
Variable '_deg' captured by a closure before being initialized
Variable '_imageSize' captured by a closure before being initialized
自分で試したこと
上のエラーが何かよくわかっていませんでしたが、とにかく値が入ってないことが問題なんだなと思い、
こちらの記事
https://www.2nd-walker.com/2020/03/13/swiftui-assign-binding-to-atbinding/
を読んで
以下のinit関数を書き加えました。
init(currentPos: Binding<CGPoint>, deg: Binding<Double>, imageSize: Binding<CGFloat>) {
self._currentPos = currentPos
self._deg = deg
self._imageSize = imageSize
}
そこで出たエラーは以下の通りです。
Initializers may only be declared within a type
Value of type 'processValue' has no member '_currentPos'
Value of type 'processValue' has no member '_deg'
Value of type 'processValue' has no member '_imageSize'
どのように記述すれば、@State変数を更新できる@Binding変数を宣言することができるのでしょうか。
また、どのようにファイル1でprocess関数を呼び出せば良いのでしょうか。
0 likes