我正在尝试创建一个简单的控制器,该控制器将在用户每次单击按钮时为您提供每分钟的节拍。我的代码编译成功,但是由于某些原因未调用button动作内的代码。对我做错的任何想法吗?
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")
}
}
}
答案 0 :(得分:1)
您需要定义一个函数,该函数可以在函数主体外部计算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
}
答案 1 :(得分:0)
在按钮动作之外编写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())
}