I want to write one function alert()
and to run it. But I want to show this alert in any controllers without repeating the code.
For example: I have Presence.swift class and here I have some condition, as:
if myVar == 1 { // Just for presenting
runMyAlert()
}
and when in the background myVar == 1
user, regardless of the fact that where he is, on which screen, he gets alert on screen.
How can I do it without repeating my code? I tried to make it in AppDelegate as:
func alert(title : String,message : String,buttonTitle : String,window: UIWindow){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.Default, handler: nil))
window.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}
And call it as:
if myVar == 1 {
AppDelegate().alert()
}
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.
来源:https://stackoverflow.com/questions/34196417/how-to-show-alert-in-all-controllers-without-repeating-the-code