【问题标题】:Call UIButton @IBAction from NSTimer function [closed]从 NSTimer 函数调用 UIButton @IBAction [关闭]
【发布时间】:2020-01-14 09:47:34
【问题描述】:

我有一个通过操作以编程方式添加的 UIButton

@objc func buttonAction(_ sender: UIButton!) {
}

我想从下面的定时器选择器调用上面的函数

@objc func preResult(timer: Timer) {
}

我该怎么做?

【问题讨论】:

  • 问题不清楚,能解释清楚吗?
  • 我想从定时器功能启动我的 UI 按钮

标签: ios swift uibutton nstimer


【解决方案1】:

按钮下方的代码 sn-p 将由计时器关闭以及用户点击按钮时调用。

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")
    }

}

【讨论】:

    【解决方案2】:

    你的意思是你想在你的定时器事件中做某事,并用你得到的结果更新你的按钮 UI?

    如果是这样,只需在活动结束时设置按钮的标题/颜色(无论您想更新什么)。并记住在主线程中执行此操作。

    DispatchQueue.main.async {
        // update UI
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      相关资源
      最近更新 更多