I'm trying to create a function where the number increases by +1 when the button is tapped, and when the button is held down, the number continues to increase only while the button is pressed.
To create this functionality, I'm trying to use both onTapGesture and onLongPressGesture in SwiftUI at the same time.
The problem is that onTapGesture and onLongPressGesture are recognized at the same time when I tap short, the number is incremented by +2.
Looking closely at why this problem exists, onLongPressGesture is still being called even when I do a short tap.
So, can't I make only onTapGesture work when I click short, and only onLongPressGesture when I press a little longer?
Thanks for reading.
import SwiftUI
struct TimerView2: View {
@State var isTimerRunning = false
@State private var timerInt = 0
@State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
func stopTimer() {
self.timer.upstream.connect().cancel()
}
func startTimer() {
self.timer = Timer.publish(every: 0.1, on: .main, in: .common).autoconnect()
}
var body: some View {
Text(String(timerInt))
.padding()
.onReceive(timer) { _ in
if self.isTimerRunning {
timerInt += 1
if timerInt > 100 {
timerInt = 100
}
}
}
.onTapGesture {
timerInt += 1
if timerInt > 100 {
timerInt = 100
}
}
.onLongPressGesture(minimumDuration: 5, maximumDistance:0, pressing: {
pressing in
if pressing {
isTimerRunning = true
self.startTimer()
} else {
isTimerRunning = false
self.stopTimer()
}
}, perform: {})
.onAppear() {
self.stopTimer()
}
}
}
struct TimerView2_Previews: PreviewProvider {
static var previews: some View {
TimerView2()
}
}