🔰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.
// ⭐️ 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?