I'm attempting to create a stepper where a number increments rapidly on a longpress gesture and stops when the user releases.
So far, I get the increment to work on the longPress, but when I release the timer still goes, continuing to increment the state.
What can I do to resolve this issue that when the user releases the press, the timer stops.
struct CustomFoodItemView: View {
@State var foodName = ""
@State var proteinAmount = 1
@State var carbAmount = 1
@State var fatAmount = 1
@State private var timer: Timer?
@State var isLongPressing = false
var body: some View {
VStack{
VStack{
Text("Food Name")
TextField("", text: $foodName)
.multilineTextAlignment(.center)
.border(.white)
.padding(.trailing, 10)
.frame(width:100, height:10)
}
HStack{
Text(String(proteinAmount) + "g")
.frame(width:50, height:50)
Image(systemName: "plus.circle.fill")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 30, height: 30)
.foregroundColor(Color("SuccessButtonColor"))
.simultaneousGesture(LongPressGesture(minimumDuration: 0.2).onChanged { _ in
print("long press")
self.isLongPressing = true
if self.isLongPressing == true{
self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { _ in
proteinAmount += 1
})
}
}
.onEnded { _ in
print("stopped") //why won't you stop
self.isLongPressing = false
})
}
}

