SwiftUI按下按钮时定期运行代码;只需轻按一下即可运行不同的代码?

问题描述 投票:0回答:1

我想做的是实现一个按钮,该按钮在按住期间每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语句,但是当我按下按钮时,它只会执行一次...如何解决此问题?

swift xcode timer swiftui gesture
1个回答
0
投票
[这是解决方案-要获得连续按下,需要将长按手势与顺序拖动相结合,并在处理程序中添加计时器。

使用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) } } }

© www.soinside.com 2019 - 2024. All rights reserved.