代码之家  ›  专栏  ›  技术社区  ›  NullHypothesis

UIButton文本未更新

  •  0
  • NullHypothesis  · 技术社区  · 10 年前

    我在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,它可以工作。

    非常感谢!

    1 回复  |  直到 10 年前
        1
  •  1
  •   NullHypothesis    10 年前

    所以我想发布一个我认为有趣的答案——我有一个不同的帐户登录到我的iPad Pro模拟器……并注意到标签正确出现。在iPhone 6中,它没有。我登录了另一个帐户。

    那么有什么区别呢?iPad pro中有大约1000000个测试行要生成,iPhone中有3个测试行,所以一切都完成得如此之快,甚至没有UI需要更新。

    我引入了一个延迟作为一个测试,并注意到实际上它是工作/导出的,所以实际上就是这样。

    事实证明,事情进展得如此之快,甚至没有时间更新到“请稍候”lol

    很抱歉打扰任何人,但请随意使用上面的代码,因为它应该可以有效地完成您需要的工作:)