未执行 bpm 代码的点击按钮

Tap button for bpm code not being executed

我正在尝试创建一个简单的控制器,它会在用户每次单击按钮时为您提供每分钟的节拍。我的代码编译成功,但按钮操作中的代码由于某种原因没有被调用。对我做错了什么有什么想法吗?

import Foundation
import UIKit

class taptempo: UIViewController {


    private var timeOutInterval = 5.0
    private var minTaps = 3
    private var taps: [NSDate] = []

    var calculatedbpm = 0

    var timeOut = 5
    var minimumTaps = 3

    @IBOutlet weak var tapnumberlabel: UILabel!
    @IBOutlet weak var tapnumberbutton: UIButton!

    override func viewDidLoad(){
        super.viewDidLoad()

        self.tapnumberlabel.text = "\(calculatedbpm)"

    }

    @IBAction func tapnumberbutaction(_ sender: Any) {

        func addTap() -> Int? {
            let thisTap = NSDate()
            if let lastTap = taps.last {
                if thisTap.timeIntervalSince(lastTap as Date) > timeOutInterval {
                    taps.removeAll()
                }
            }
            taps.append(thisTap)
            guard taps.count >= minTaps else { return nil }
            guard let firstTap = taps.first else { return 0 }
            let avgIntervals = thisTap.timeIntervalSince(firstTap as Date) / Double(taps.count - 1)
            calculatedbpm = Int((60.0 / avgIntervals))
            self.tapnumberlabel.text = "\(calculatedbpm)"
            print(calculatedbpm)
            return calculatedbpm

           // print("func not working")
        }
    }
}

您需要在函数体之外定义一个计算bmp 的函数。在按钮操作中只需调用它并更新 ui.

@IBAction func tapnumberbutaction(_ sender: Any) {
    self.tapnumberlabel.text = "\(addTap() ?? 0)" // conditional unwrap of returned value
}

func addTap() -> Int? {
    let thisTap = NSDate()
    if let lastTap = taps.last {
        if thisTap.timeIntervalSince(lastTap as Date) > timeOutInterval {
            taps.removeAll()
        }
    }
    taps.append(thisTap)
    guard taps.count >= minTaps else { return nil }
    guard let firstTap = taps.first else { return 0 }
    let avgIntervals = thisTap.timeIntervalSince(firstTap as Date) / Double(taps.count - 1)
    calculatedbpm = Int((60.0 / avgIntervals))
    print(calculatedbpm)
    return calculatedbpm
}

在按钮操作之外编写 addTap() 函数。然后从按钮的 Action 中调用 addTap() 函数。

func addTap() -> Int? {

        let thisTap = NSDate()
        if let lastTap = taps.last {
            if thisTap.timeIntervalSince(lastTap as Date) > timeOutInterval {
                taps.removeAll()
            }
        }
        taps.append(thisTap)
        guard taps.count >= minTaps else { return nil }
        guard let firstTap = taps.first else { return 0 }
        let avgIntervals = thisTap.timeIntervalSince(firstTap as Date) / Double(taps.count - 1)
        calculatedbpm = Int((60.0 / avgIntervals))
        return calculatedbpm

       // print("func is working")
    }

 @IBAction func tapnumberbutaction(_ sender: Any) {

     self.tapnumberlabel.text = String(addTap())                             
  }