简体   繁体   中英

Defining UIAlert in a separate class file, then invoking it from any view controller

In order to avoid duplicate code, I would like to create a separate class file to handle all errors in my app (mostly returned from backend blocks) and present them to the user in an alert popup that user can close. So I've created a class, and put this inside:

import Foundation

class Errors {

func errors(errorText: String, currentViewController: UIViewController) {

    var alert = UIAlertController(title: "There was an error", message: errorText, preferredStyle: UIAlertControllerStyle.Alert)

    alert.addAction(UIAlertAction(title: "Close", style: .Default, handler: nil))


    currentViewController.presentViewController(alert, animated: true, completion: nil)


    }
}

then when invoking this function from any viewController I do this:

            Errors().errors("Error text", currentViewController: GameScreenViewController)

this won't work and compiler wants me to add () after GameScreenViewController which cause the app to behave improperly.

I guess this is not the right way to do this, can you please advise on how to do this properly. Please answer in Swift.

you need to invole it with 'self' instead of GameScreenViewController as second argument from within your view controller you like to display the error.

what you are passing currently is not an object but merely a classname.

class GameScreenViewController : UIViewConroller {

    // your viewcontroller logic

    func showError(){
        // try this:
        Errors().errors("Error text", currentViewController: self)
    }

}

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