create alert function in all view controllers - swift

半城伤御伤魂 提交于 2019-12-19 04:23:32

问题


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)
    }

}

回答1:


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

1. If you want to display alert each time view did appear:

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")
    }

}

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
    }
}

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

2. If you want to display alert on 'demand':

As suggested, extend UIViewController

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



回答2:


Use an extension like this

extension UIViewController {
  func showAlert(title: String, message: String) {
    let alertController = UIAlertController(title: title, message:
      message, preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {action in
    }))
    self.present(alertController, animated: true, completion: nil)
  }
}

call the function like this

self.showAlert(title: "hi", message: "test")



回答3:


Actually you can declare a simple method anywhere outside class.

func showAlertWithCompletion(message:String,okTitle:String,cancelTitle:String?,completionBlock:@escaping (_ okPressed:Bool)->()){
    let alertController = UIAlertController(title: AppName, message: message, preferredStyle: .alert)
    let okAction = UIAlertAction(title: okTitle, style: .default) { (ok) in
        completionBlock(true)
    }
    alertController.addAction(okAction)
    if let cancelTitle = cancelTitle{
        let cancelOption = UIAlertAction(title: cancelTitle, style: .cancel, handler: { (axn) in
            completionBlock(false)

        })
        alertController.addAction(cancelOption)
    }

    if let topController = UIWindow.topViewController(){
      topController.present(alertController, animated: true, completion: nil)
    }

}

This way wherever you call it, you will get ok button pressed callback in completion handle or even make Extension as described by @Ganesh Kumar




回答4:


Why not just an extension

extension 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)
    }
}



回答5:


You could create extension to alertController and also have option for action handler. This will allow to use two different Alert controller based on handler is required or not.

extension  UIAlertControler {

class func genericErrorAlert(forAlert message: String, completion: ((UIAlertAction) -> Void)? = nil )

    let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)

    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: completion))

    return alert
  }
}



回答6:


You can also create one util file in your app, in that you can add any reusable method or function and use it anywhere in your app Like,

import Foundation import UIKit

//MARK: - ALERT

func showMessage(title: String, message: String!, VC: UIViewController) {

let alert : UIAlertController = UIAlertController(title: "", message: message, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
    UIAlertAction in
}
alert.addAction(okAction)
VC.present(alert, animated: true, completion: nil)

}




回答7:


You can use this view controller extension to present alert view across the application. https://github.com/SumitKr88/UIViewController-ShowAlertView/blob/master/UIViewController%2BExtensions.swift

extension UIViewController {

/// Show alert view
/// - Parameter title: title of alert
/// - Parameter message: message of alert
/// - Parameter actionTitles: List of action button titles(ex : "OK","Cancel" etc)
/// - Parameter style: Style of the buttons
/// - Parameter actions: actions repective to each actionTitles
/// - Parameter preferredActionIndex: Index of the button that need to be shown in bold. If nil is passed then it takes cancel as default button.

/**
 Example usage:-
 Just make sure actionTitles and actions array the same count.

 /********** 1. Pass nil if you don't need any action handler closure. **************/
 self.showAlert(title: "Title", message: "message", actionTitles: ["OK"], style: [.deafult], actions: [nil])

 /*********** 2. Alert view with one action **************/

 ///     let okActionHandler: ((UIAlertAction) -> Void) = {(action) in
 //Perform action of Ok here
 }
 self.showAlert(title: "Title", message: "message", actionTitles: ["OK", "CANCEL"], style: [.default, .cancel], actions: [okayActionHandler, nil])

 /********** 3.Alert view with two actions **************/

 let okActionHandler: ((UIAlertAction) -> Void) = {(action) in
 //Perform action of ok here
 }

 let cancelActionHandler: ((UIAlertAction) -> Void) = {(action) in
 //Perform action of cancel here
 }

 self.showAlert(title: "Title", message: "message", actionTitles: ["OK", "CANCEL"], style: [.default, .cancel], actions: [okActionHandler,cancelActionHandler], preferredActionIndex: 1)
 */

public func showAlert(title: String?,
                      message: String?,
                      actionTitles: [String?],
                      style: [UIAlertAction.Style],
                      actions: [((UIAlertAction) -> Void)?],
                      preferredActionIndex: Int? = nil) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    for (index, title) in actionTitles.enumerated() {
        let action = UIAlertAction(title: title, style: style[index], handler: actions[index])
        alert.addAction(action)
    }
    if let preferredActionIndex = preferredActionIndex { alert.preferredAction = alert.actions[preferredActionIndex] }
    self.present(alert, animated: true, completion: nil)
}}


来源:https://stackoverflow.com/questions/43363816/create-alert-function-in-all-view-controllers-swift

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