简体   繁体   中英

Xcode, swift: alert not dismissing

class AVC: UIViewController {
    override func viewDidLoad(){
        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.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
        loadingIndicator.startAnimating();

        alert.view.addSubview(loadingIndicator)
        viewController.present(alert, animated: true, completion: nil)
        self.a()
    }

    func a(){
        ZZZ.remove(for: self)
    }
}

class ZZZ {

    func remove(for viewController: UIViewController){
        viewController.dismiss(animated: false, completion: nil)
        //Why won't the alert created in AVC be dismissed from here?
    }
}

Hi there,
I have a view controller AVC that creates an alert & a loading indicator.
I wish to dismiss this alert from another swift file called ZZZ using ZZZ's remove function.
However, the alert is not dismissed from ZZZ even though my code clearly asks it to.
How do I fix this?
Thanks

You are currently dismissing the viewcontroller, not alert. Call

alert.dismiss(animated: false, completion: nil)


func a() {
        ZZZ().remove(for: alert)
}

Here shared is custom class for showing alert

class Shared: NSObject {
    func waitAlert() -> UIAlertController {
        let alert = UIAlertController(title: nil, 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)
        return alert
    }
}

So in your viewcontroller you can for showing alert

let alert = Shared().waitAlert()
present(alert, animated: true, completion: {
   alert.dismiss(animated: true, completion: {
    //do your code
   })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM