🔰update gesture states
SwiftUI ⟩ Gestures ⟩ update gesture states
Gesture state is "transient" which means it will reset back to its initial state when user ends or cancels the gesture.
To update a view as a gesture changes, add a
GestureState
property to your view and update it withupdating(_:body:)
.SwiftUI invokes the updating callback as soon as it recognizes the gesture and whenever the value of the gesture changes.
SwiftUI doesn’t invoke the updating callback when the user ends or cancels a gesture. Instead, the gesture state property automatically resets its state back to its initial value.
// ⭐️ updates @GestureState var as the gesture’s value changes.
// `updating($state){ value, state, transaction in ... }`
func updating<State>(
_ state: GestureState<State>,
body: @escaping (
Self.Value, // gesture's current value
inout State, // @GestureState var to be updated
inout Transaction // animation "context" (❓)
) -> Void
) -> GestureStateGesture<Self, State>
⬆️ 需要: TimerView
struct ContentView: View {
// ⭐️ gesture state:
// reset to initial value when ends or cancels.
@GestureState var isPressing = false
var body: some View {
// long press (for 3 sec)
let press = LongPressGesture(minimumDuration: 3)
// ⭐️ update gesture state
.updating($isPressing) { value, state, _ in
state = value
}
return Circle()
.fill(isPressing ? .pink : .green)
.frame(width: 100, height: 100, alignment: .center)
.gesture(press) // ⭐️ apply gesture
.overlay {
if isPressing {
// 👔 TimeView: count-down timer
TimerView(seconds: 3) { sec in
Text("\(sec)").font(.system(size: 50)).bold()
}
}
}
}
}
問:「 .updating() 的 body closure 的第三個參數 transaction 是幹什麼的❓」
問:「 .updating() 似乎只能更新 GestureState,不能更新 @State 變數❓」
答:「 更新 view states 要用 .onChanged() 」
Last updated
Was this helpful?