根据 2 个“onTap”之间的持续时间触发 2 个不同的操作

trigger 2 different actions depending on duration between 2 ‘onTap’

对于一个按钮,每次点击时,如何在 'onTap' 发生时间少于 60 秒时触发代码 1(将特定变量设置为值 1)或在 onTap 发生时触发代码 2(将特定变量设置为值 2)发生在 60 多秒前?

==> 实施持续时间 = 10 秒的工作解决方案

Button(action: {
            self.date = Date()
            let hour = self.calendar.component(.hour, from: self.date)
            let minutes = self.calendar.component(.minute, from: self.date)
            let seconds = self.calendar.component(.second, from: self.date)
            self.newdate = hour*3600+minutes*60+seconds
    
            if (self.lastdate == 0){
                print(" First Tap...")
            }else
            if (self.newdate-self.lastdate) < 10  {
                    print("Tap before 10 sec =>  call Func1")
                    
                } else {
                print("Tap > 10 seconds => call Func2")
                           }
            self.lastdate = hour*3600+minutes*60+seconds
           
                         }) {
            Text("One")
                            }
    var lastTapTimestamp: Date?

    @IBAction func buttonTapped(_ sender: UIButton) {
        defer { lastTapTimestamp = Date() }
        guard let date = lastTapTimestamp else {
            callFunc1()
            return
        }
        if Int(Date().timeIntervalSinceReferenceDate) - Int(date.timeIntervalSinceReferenceDate) >= 3600 {
            callFunc2()
        } else {
            callFunc1()
        }
    }

这里有一个完整的例子,间隔 5 秒(为了加快测试速度)。

它使用 @State 变量来更新 lastTapmessageDate 并使用 .timeIntervalSince(last) 以秒为单位测量时间。当 lastTap 仍然是 nil 时检测到第一次点击。

更改 message 会导致视图重绘并更新屏幕上的消息。

struct ContentView: View {
    
    @State private var lastTap: Date? = nil
    @State private var message = ""
    
    var body: some View {
        VStack(spacing: 40) {
            Text(message)
            Button("Tap me") {
                let now = Date()
                if let last = self.lastTap {
                    if now.timeIntervalSince(last) > 5 {
                        self.message = "Greater than 5 seconds"
                    } else {
                        self.message = "Less than 5 seconds"
                    }
                } else {
                    self.message = "First tap"
                }
                self.lastTap = now
            }
        }
    }
}