在所有视图控制器中创建警报功能

编程入门 行业动态 更新时间:2024-10-24 14:19:42
本文介绍了在所有视图控制器中创建警报功能-迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试声明一个用于在我的应用中显示警报的函数.为了避免重复工作,我正在尝试对所有应用程序使用相同的功能.我试图通过创建带有函数showNotification的类来做到这一点.但是当我创建该类的对象并调用该方法时,什么也没发生.我该怎么办?

I'm trying to declare a function for showing alerts in my app. To avoid repeating work, i'm trying to use same function for all my app. I tried to do that by creating a class with function showNotification. but when i create an object of that class and call the method, nothing happens. How can i do that?

class SharedPropertiesAndMetods : UIViewController { func showNotification(title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "تائید", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } }

推荐答案

我要做的是创建一个通用"视图控制器来完成工作并从中继承:

What I would do is to create a 'generic' view controller that do the job and than inherit from it:

1.如果您希望每次显示视图时都显示警报,则:

class GenericViewController: UIViewController { // MARK: - View lifecycle - override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let notification = self.shouldDisplayAlertNotification() { self.showNotification(notification) } } // MARK: - Internal methods - func shouldDisplayAlertNotification() -> AlertNotification? { return nil } // MARK: - Private methods - private func showNotification(_ alertNotification: AlertNotification) { } } class MyController: GenericViewController { override func shouldDisplayAlertNotification() -> AlertNotification? { return AlertNotification(title: "Title", message: "Message") } }

其中AlertNotification是您的自定义模型类:

Where AlertNotification is your custom model class:

class AlertNotification { var title: String var message: String init(title: String, message: String) { self.title = title self.message = message } }

通过这种方式,只有覆盖shouldDisplayAlertNotification的VC才会显示警报.

In this way, only VC that overrides shouldDisplayAlertNotificationwill display alert.

2.如果要在需求"上显示警报:

根据建议,扩展UIViewController

As suggested, extend UIViewController

extension UIViewController { func showNotification(title: String, message: String) { } }

更多推荐

在所有视图控制器中创建警报功能

本文发布于:2023-11-27 15:57:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   警报   器中   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!