【发布时间】:2020-06-13 00:12:01
【问题描述】:
我想要做的是实现一个按钮,它在被按住时每 0.5 秒运行一次特定的代码行(它可以无限期地按住,从而无限期地运行打印语句)。我希望它在被点击时有不同的行为。代码如下:
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
}
)
}
}
}
目前,这与我需要它做的有点相反;当我单击一次按钮时,上面的代码无限期地运行打印语句,但是当我按住它时,它只执行一次......我该如何解决这个问题?
【问题讨论】:
标签: swift xcode timer swiftui gesture