【发布时间】:2016-01-02 17:20:36
【问题描述】:
我在我的 iOS Swift 应用程序中使用的一个“久经考验”的模式是我有几个带有 UIButtons 的区域。当按下按钮时,它会触发一些连接到我的 API 的网络代码。发生这种情况时,我让按钮文本说“请稍候,正在加载”,然后我禁用了该按钮。当队列中的操作在我的回调中完成时,我启用了按钮文本并更改回原始状态。效果很好。
我最近添加了一些不使用 NSURL/NSDATA 的东西(它只是一个文件编写器)。我复制了所有相同的 GCD 队列代码,奇怪的是它没有更新按钮文本。
这是我的代码。当您点击按钮时,文本将变为不可见,直到回调完成,然后它才恢复。奇怪的是,如果我将模拟器更改为 iPad Pro,它实际上可以工作(??)并说“请稍候,正在下载”。如果我换成 iPhone 6s 就不行了。
@IBAction func btnGenerateCSV(sender: UIButton) {
//Grab the original text of the button to restore later after done
let originalButtonText = sender.titleForState(UIControlState.Normal)
//Localized is an extension function I wrote.
//As you can see I got crazy here adding all the UI States as a last ditch attempt to see if that was the reason.
sender.setTitle(Localized("Downloading"), forState: UIControlState.Normal)
sender.setTitle(Localized("Downloading"), forState: UIControlState.Disabled)
sender.setTitle(Localized("Downloading"), forState: UIControlState.Highlighted)
//I've tried moving this before the setTitle. No avail.
sender.enabled = false
//I've tried the other queues as well, and even just tried dispatch_async(dispatch_get_main_queue()) but no luck
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
CsvReportWriter.GenerateReport()
{
r in
dispatch_async(dispatch_get_main_queue()) {
FileManager.WriteToFile(r, filename: self.filename)
if FileManager.FileExists(self.filename) {
self.docController = UIDocumentInteractionController(URL: FileManager.GetURLOfFile(self.filename))
self.docController.presentOptionsMenuFromRect(sender.frame, inView:self.view, animated:true)
}
//Restore button state and text b/c we're done
sender.enabled = true
sender.setTitle(originalButtonText, forState: UIControlState.Normal)
}
}
}
}
有什么想法吗?如果我将 CsvReportWriter.GenerateReport() 代码换成其他一些调用我的 API 的异步代码,它就可以工作。
非常感谢!
【问题讨论】:
-
可能有点离题,但请注意,在 Swift 2 中,
OptionSetType成员的Self--- 用于forState参数,例如 @987654327 的方法.setTitle@---可以推断,所以你需要t writeforState: UIControlState.Normal;forState: .Normal`就足够了。此外,当您为三个不同的状态设置相同的标题时,OptionSetType允许您一次为所有这些状态设置属性,例如forState: [.Normal, .Disabled, .Highlighted]在一行中。详情请见stackoverflow.com/questions/34502753/…。
标签: ios swift uibutton ios9 grand-central-dispatch