2017-02-06 57 views
1

我嘗試使用主線程來顯示,但它沒有工作,任何思想爲什麼警報不馬上顯示?Swift - 單擊按鈕後立即顯示警告與加載指示器的最佳方式?

@IBAction func updateData(_ sender: Any) { 
    let alert = UIAlertController(title: "Updating data", message: "Please wait...", preferredStyle: .alert) 
    alert.view.tintColor = UIColor.black 
    let loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 10,y: 5,width: 50, height: 50)) as UIActivityIndicatorView 
    loadingIndicator.hidesWhenStopped = true 
    loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray 
    loadingIndicator.startAnimating(); 

    alert.view.addSubview(loadingIndicator) 
    DispatchQueue.main.async { 
     self.present(alert, animated: true) 

    } 
+0

目前有之前的警報顯示延遲了 – QTB

+0

任何理由你正在主隊列上調度它?而不是直接展示它。 存在(警報,動畫:真) – vj9

+0

我前面已經有這個問題,似乎當的viewController是我最初的視圖控制器僅發生,但如果我Segue公司到控制器,它似乎做工精細 – Mentos

回答

0

我跑這通過Xcode中沒有任何延遲:

@IBAction func updateData(_ sender: UIButton) { 
    print("button fire") 
    let alert = UIAlertController(title: "Updating data", message: "Please wait...", preferredStyle: .alert) 
    alert.view.tintColor = UIColor.black 
    let loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 10,y: 5,width: 50, height: 50)) as UIActivityIndicatorView 
    loadingIndicator.hidesWhenStopped = true 
    loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray 
    loadingIndicator.startAnimating(); 

    alert.view.addSubview(loadingIndicator) 
    self.present(alert, animated: true) 

} 

我換成你的函數的參數senderUIButton,拿出調度呼叫到主隊列,因爲它是不必要的。沒有任何延誤!

當你說有延遲時,你的意思是隻有當你通過代碼?因爲如果您正在瀏覽它,則在self.present(alert, animated: true)之後不會立即顯示警報視圖。你必須等到函數完成執行。但這種「延遲」對人眼來說是不可見的。你有沒有嘗試運行上面的代碼,而沒有通過它?

3

UIAlertController無法自定義,所以對我來說最好的解決方案是創建一個自定義的UIView XIB,然後將其安裝在我需要的ViewController上。

的廈門國際銀行視圖可能是這樣的: XIB View

然後創建該子類UIView,它關聯到廈門國際銀行,並創建一個IBOutlets文件CustomAlertLoadingView.swift。

在任何ViewController顯示它只是創建這個擴展

extension UIViewController { 
    func presentAlert(title: String) { 
     let nib = UINib(nibName: "CustomAlertLoadingView", bundle: nil) 
     let customAlert = nib.instantiate(withOwner: self, options: nil).first as! CustomAlertLoadingView 

     customAlert.tag = 12345 
     customAlert.titleAlertLabel.text = title 
     customAlert.indicator.startAnimating() 


     let screen = UIScreen.main.bounds 
     customAlert.center = CGPoint(x: screen.midX, y: screen.midY) 

     self.view.addSubview(customAlert) 
    } 
} 

使用self.yourViewController.presentAlert(title:"yourTitle")

要解除警報,創建此功能UIVIewController擴展

func dismissCustomAlert() { 
     if let view = self.view.viewWithTag(12345) { 
      view.removeFromSuperview() 
     } 
} 

裏面然後調用self.yourViewController.dismissCustomAlert

+0

這個應該是被接受的答案!謝謝 – Lucas

1

我只好把需要執行的代碼在警報完成回調

self.present(alert, animated: true, completion: { 
     do{...} 

})

是解決了延遲響應