【问题标题】:Swift: How to disable a buttonSwift:如何禁用按钮
【发布时间】:2016-12-09 18:15:57
【问题描述】:

我正在尝试禁用某个按钮一段时间,但遇到了问题。我的程序如下:

  1. 我有 3 个按钮,所有按钮都已启用
  2. 单击一个按钮后,禁用所有按钮。同时,通过蓝牙发送数据...
  3. 完成发送数据后启用所有按钮。

我的目标是防止在通过蓝牙发送数据时单击按钮。我尝试使用Button.userInteractionEnabled = falseButton.enabled = false,但是每当我在完成发送数据后启用按钮时,它会再次转到按钮操作处理程序(我在数据发送期间按下的那个)。有谁知道如何在一定时间内永久禁用按钮?

【问题讨论】:

  • 您是说点击已处理,但有延迟? (使用isEnabled = false时。)
  • 此处需要实际代码。

标签: swift button


【解决方案1】:

您要做的是在单击时禁用按钮,然后在数据传输完成时以某种方式启用它。

如果此数据传输是异步调用的,它可能会有一个参数,您可以在其中发送一个完成块

button.isUserInteractionEnabled = false
sendData(data) {
    success in
    button.isUserInteractionEnabled = true
}

如果它不接受 completion block 作为参数,它可能会以不同的方式工作,例如使用 notifications(触发具有特定名称的通知):

button.isUserInteractionEnabled = false
sendData(data)

// adding the observer that will watch for the fired notification
NotificationCenter.default.addObserver(self, selector: #selector(self.didFinishSendingData(_:)), name: Notification.Name(rawValue: "NOTIFICATION NAME GOES HERE"), object: nil)

func didFinishSendingData(_ notification: Notification?) {
    button.isUserInteractionEnabled = true
}

如果您发布代码示例,我们绝对可以提供更多帮助。

【讨论】:

    【解决方案2】:

    为什么你可以在main thread 上使用activityIndicator 来实现这一点,如下所示:

        let activityIndicator = UIActivityIndicatorView()
        activityIndicator.frame = view.frame
        activityIndicator.center = view.center
        activityIndicator.activityIndicatorViewStyle = .gray
        activityIndicator.hidesWhenStopped = true
        view.addSubview(activityIndicator)
    
        //start activity indicator
        activityIndicator.startAnimating()
    
        //send your data via bluetooth on main thread
        DispatchQueue.main.async {
            //put your sending via bluetooth code here with a completion handler when completes
            //then in the completion handler, put below line
            activityIndicator.stopAnimating()
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 2016-03-05
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多