我想做的是实现一个按钮,该按钮在按住期间每0.5秒运行一行特定的代码(可以无限期按住它,从而无限期地运行print语句)。我希望它在点击时具有不同的行为。这是代码:
struct ContentView: View {
@State var timeRemaining = 0.5
let timer = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
@State var userIsPressing = false //detecting whether user is long pressing the screen
var body: some View {
VStack {
Image(systemName: "chevron.left").onReceive(self.timer) { _ in
if self.userIsPressing == true {
if self.timeRemaining > 0 {
self.timeRemaining -= 0.5
}
//resetting the timer every 0.5 secdonds and executing code whenever //timer reaches 0
if self.timeRemaining == 0 {
print("execute this code")
self.timeRemaining = 0.5
}
}
}.gesture(LongPressGesture(minimumDuration: 0.5)
.onChanged() { _ in
//when longpressGesture started
self.userIsPressing = true
}
.onEnded() { _ in
//when longpressGesture ended
self.userIsPressing = false
}
)
}
}
}
目前,这与我需要执行的操作相反;当我单击一次按钮时,上面的代码无限期地运行print语句,但是当我按下按钮时,它只会执行一次...如何解决此问题?
使用Xcode 11.4 / iOS 13.4测试
struct TestContinuousPress: View {
@State private var timer = Timer.publish(every: Double.infinity, on: .main, in: .common).autoconnect()
@State var userIsPressing = false //detecting whether user is long pressing the screen
@GestureState var pressingState = false // will be true till tap hold
var pressingGesture: some Gesture {
LongPressGesture(minimumDuration: 0.5).sequenced(before:
DragGesture(minimumDistance: 0, coordinateSpace:
.local)).updating($pressingState) { value, state, transaction in
switch value {
case .second(true, nil):
self.userIsPressing = true
self.timer = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
default:
break
}
}.onEnded { _ in
self.userIsPressing = false
self.timer = Timer.publish(every: Double.infinity, on: .main, in: .common).autoconnect()
}
}
var body: some View {
VStack {
Image(systemName: "chevron.left")
.onReceive(self.timer) { _ in
print(">>>> pressing: \(Date())")
}
.gesture(TapGesture().onEnded {
print("> just tap ")
})
.gesture(pressingGesture)
}
}
}