我有一个以编程方式添加了动作的UIButton
@objc func buttonaction(_ sender: UIButton!) {
}
我想从计时器选择器下方调用上述函数
@objc func preResult(timer: Timer) {
}
我该怎么办?
在按钮动作下方带有代码段的情况下,计时器关闭程序将在用户单击按钮时调用该按钮动作。
import UIKit
class ViewController: UIViewController {
var button: UIButton = UIButton(frame: CGRect(x: 0,y: 0,width: 100,height: 40))
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))
})
// Add a button to a view
view.addSubview(button)
// Assign a function to call when a button is tapped
button.addTarget(self,action: #selector(buttonAction),for: .touchUpInside)
}
@objc func buttonAction() {
print("button tapped")
}
}
,
您是说要在计时器事件中执行某项操作,并用得到的结果更新按钮UI吗?
如果是这样,只需在活动结束时设置按钮的标题/颜色(无论您要更新什么)。并记住在主线程中执行该操作。
DispatchQueue.main.async {
// update UI
}