How to show alert in all controllers without repeating the code?

醉酒当歌 提交于 2019-12-06 11:12:35

Developing on Swift you should know about protocols which can solve your problem easily. You can create a new protocol MyAlert and make default implementation for UIViewController class. And then just inherit your MyAlert protocol in view controller, where you need it, and call the function!

protocol MyAlert {
    func runMyAlert()
}

extension MyAlert where Self: UIViewController {
    func runMyAlert() {
        let alert = UIAlertController(title: title, message: "message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "buttonTitle", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

So you can implement and call it like that:

class MyViewController: UIViewController, MyAlert {
    override func viewDidLoad() {
        runMyAlert() // for test
    }
}

UPD:

code for your case:

protocol MyAlert {
    func runMyAlert()
}

extension MyAlert where Self: UIViewController {
    func runMyAlert() {
        let alert = UIAlertController(title: title, message: "message", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "buttonTitle", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

class OpenChatsTableViewController: UITableViewController, MyAlert, OneRosterDelegate, BuddyRequestProtocol {
    override func viewDidLoad() {
        runMyAlert()
    }
}

Create a category on UIViewController, write a method there, calling which app will show an alert box.

Now create a new BaseViewController which will be inherited from UIViewController. Import your category in this BaseViewController;

From this point, whenever you create a new viewController, select your base class type as BaseViewController not UIViewController.

By doing so, you can call that alert showing method from anywhere.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!