我以编程方式用按钮做了一个小程序
@objc func buttonAction(_ sender: UIButton!) {
}
@objc func preResult(timer: Timer) {
}
我想添加计时器并想转移到我按钮的“ func preResult
” UI中
我该怎么办?
您是说要在计时器事件中做某事,并使用得到的结果更新按钮UI?
如果是这样,只需在活动结束时设置按钮的标题/颜色(无论您要更新什么)。并记住在主线程中执行此操作。
DispatchQueue.main.async {
// update UI
}
import UIKit
class ViewController: UIViewController {
@IBOutlet var button: UIButton!
var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
// Create a timer which will call a closure with an argument timer
timer = Timer.scheduledTimer(withTimeInterval: 4, repeats: true, block: { (timer) in
self.perform(#selector(self.buttonAction))
})
// Assign a function to call when a button is tapped
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
}
@objc func buttonAction() {
print("button tapped")
}
}