我想做的是实现一个按钮,该按钮在按下时每0.5秒运行一行特定的代码(可以无限次按下它,从而无限期地运行print语句)。我希望它在点击时具有不同的行为。这是代码:
filter()
此刻,这与我需要执行的操作有点相反;上面的代码在我单击一次按钮时无限期地运行print语句,但是当我按下按钮时,它只会执行一次...如何解决此问题?
答案 0 :(得分:1)
这是一个解决方案-要获得连续按下,需要将长按手势与顺序拖动相结合,并在处理程序中添加计时器。
已更新:已在Xcode 11.4 / iOS 13.4(在预览版和模拟器中)进行了测试
struct TimeEventGeneratorView: View {
var callback: () -> Void
private let timer = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
var body: some View {
Color.clear
.onReceive(self.timer) { _ in
self.callback()
}
}
}
struct TestContinuousPress: View {
@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):
state = true
default:
break
}
}.onEnded { _ in
}
}
var body: some View {
VStack {
Image(systemName: "chevron.left")
.background(Group { if self.pressingState { TimeEventGeneratorView {
print(">>>> pressing: \(Date())")
}}})
.gesture(TapGesture().onEnded {
print("> just tap ")
})
.gesture(pressingGesture)
}
}
}