[英]Alert ViewController with Activity Loader Getting Warning and not Dismissing Swift
我的場景是,我試圖在AlertViewController
創建Loader。 在這里,我受到警告的警告,並且不允許在兩次審判后被解雇。 我在一個普通的類中使用下面的函數,並在多個viewController中重用。
我的密碼
// MARK: Common AlertView
extension UIViewController {
func loadinHubShow() {
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.style = UIActivityIndicatorView.Style.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: true, completion: nil)
}
func loadinHubDismiss() {
dismiss(animated: false, completion: nil)
}
}
其他ViewController
func dataJson() {
// Start Loading
self.loadinHubShow()
// after process done
DispatchQueue.main.async {
self.loadinHubDismiss()
}
}
我的警告
警告:在演示或關閉過程中,請嘗試從視圖控制器中關閉!
如我所見,您正在使用此功能作為UIViewController
擴展。
實現結果的一種方法是獲得對您正在使用的警報的引用。
注意:如果您像以前一樣使用
dismiss
函數,那么您將試圖關閉viewController而不是警報,這就是為什么收到該警告的原因。
嘗試通過以下方式更改擴展功能:
1) loadinHubShow
將返回對alert
的reference
func loadinHubShow() -> UIAlertController {
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.style = UIActivityIndicatorView.Style.gray
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
return alert
//You don't have to present the alert here
//present(alert, animated: true, completion: nil)
}
2) loadinHubDismiss
將刪除該alert
:
func loadinHubDismiss(alert: UIAlertController) {
alert.dismiss(animated: false, completion: nil)
}
為了使用這些功能,我們假設您擁有ViewController
:
class ViewController: UIViewController{
var myAlert: UIAlertController = UIAlertController()
override func viewDidLoad(...){
myAlert = self.loadinHubShow()
//now you can present or dismiss the alert wherever you want
//for example:
self.present(myAlert,animated: false, completion: nil)
//when you want dismiss the alert, just call:
self. loadinHubDismiss(alert: myAlert)
}
}
編輯
按照建議關閉alert
,請嘗試:
DispatchQueue.main.async{
loadinHubDismiss(alert: myAlert)
}
問題與您執行同步json解析過程有關,該過程導致
func dataJson() {
self.loadinHubShow()
// after process done
DispatchQueue.main.async {
self.loadinHubDismiss()
}
}
在完成警告之前將其關閉以顯示警告,因此可以完全刪除等待的警報或使用dispatchAfter
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.loadinHubDismiss()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.