๐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 โฉ
Gestures โฉ Gesture (protocol)
.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