👆Gestures
⭐️ .updating()
update gesture states (fires as soon as it recognizes the gesture and whenever the value of the gesture changes. )
⭐️ .onChanged()
updates permanent view state whenever the value of the gesture changes.
⭐️ .onEnded()
updates permanent view state when gesture successfully ends. (fires when a gesture successfully completes and receives its final value.)
GestureState - transient gesture states
📗 參考:Adding Interactivity with Gestures ⭐️
⬆️ 需要: TimerView (for countdown)
struct ContentView: View {
// ⭐️ gesture state is "transient"
// (reset to initial value when gesture ends or cancelled)
@GestureState var isPressing = false
// ⭐️ view states are "permanent" (won't reset)
@State private var tapCount = 0
@State private var longPressCount = 0
@State private var isCounting = true
/// long press
var longPress: some Gesture {
LongPressGesture(minimumDuration: 3) // for 3 sec
// ⭐️ update gesture state (while pressing)
.updating($isPressing) { value, state, _ in
state = value
}
// ⭐️ update view state (when tap/press is detected)
// ❗️ 注意:這是「摸到」就會觸發,不是「長按」才會觸發。
// 🔸 [註] 官網上寫:
// count the number of times your app recognizes a "long press"
// 是錯誤的,應該是:
// ... recognizes a "tap"❗️
.onChanged { _ in
tapCount += 1
}
// ⭐️ update view states when gesture (successfully) ends.
.onEnded { _ in
isCounting = false
longPressCount += 1
}
}
var body: some View {
VStack {
Text("tap count: \(tapCount)")
Text("long press count: \(longPressCount)")
Circle()
.fill(isPressing ? .pink : .green)
.frame(width: 100, height: 100, alignment: .center)
// ⭐️ apply gesture if is counting taps
.gesture(isCounting ? longPress : nil)
.overlay {
if isPressing {
// ⭐️ count-down timer
TimerView(seconds: 3) { sec in
Text("\(sec)").font(.system(size: 50)).bold()
} // 👔 TimeView
}
}
// optional view
if !isCounting {
Text("long press gesture disabled\nsorry, no more taps.")
.font(.caption)
.foregroundColor(.secondary)
}
}
}
}
SwiftUI ⟩
.updating(_:body:) - update gesture state as gesture’s value changes.
.onChanged(_:) - perform an action when gesture’s value changes.
問:「 .updating() 與 .onChanged() 到底有什麼差別❓」
答:「 .updating() 更新 gesture states,.onChanged() 更新 view states。」
Last updated