如何在不重复代码的情况下在所有控制器中显示警报? [英] How to show alert in all controllers without repeating the code?
问题描述
我想编写一个函数 alert()
并运行它。但是我想在任何控制器中显示此警报而无需重复代码。
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.
例如:我有Presence.swift类,这里有一些条件,例如:
For example: I have Presence.swift class and here I have some condition, as:
if myVar == 1 { // Just for presenting
runMyAlert()
}
并且在后台 myVar == 1
用户时,无论事实上,他在哪里,在哪个屏幕上,他都会在屏幕上得到警报。
and when in the background myVar == 1
user, regardless of the fact that where he is, on which screen, he gets alert on screen.
如何在不重复代码的情况下做到这一点?我试图在AppDelegate中使它成为:
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)
}
并将其称为:
if myVar == 1 {
AppDelegate().alert()
}
推荐答案
在 Swift
您应该了解可以轻松解决问题的协议。您可以创建一个新协议 MyAlert
并为 UIViewController
类设置默认实现。然后只需在需要的地方在视图控制器中继承您的 MyAlert
协议,然后调用该函数即可!
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:
您的案例代码:
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()
}
}
这篇关于如何在不重复代码的情况下在所有控制器中显示警报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!