Swift:如何禁用按钮

时间:2016-12-09 18:15:57

标签: swift button

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

  1. 我有3个按钮,所有按钮都已启用
  2. 单击一个按钮后,禁用所有按钮。在此期间,通过蓝牙发送数据......
  3. 完成发送数据后启用所有按钮。
  4. 我的目标是在通过蓝牙发送数据时阻止按钮单击。我尝试使用Button.userInteractionEnabled = falseButton.enabled = false,但只要在完成发送数据后启用按钮,它就会再次转到按钮操作处理程序(我在数据发送期间按下的那个)。有没有人知道如何在一定时间内永久禁用按钮?

2 个答案:

答案 0 :(得分:0)

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

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

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

如果它不接受完成块作为参数,它可能以不同的方式工作,例如使用通知(使用触发通知具体名称):

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
}

如果您发布代码示例,我们肯定会提供更多帮助。

答案 1 :(得分:0)

为什么可以使用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() } 上实现此目的:

$variable