-2

I have used side navigation menu(SWReveal). I have 4 ViewControllers. How can use same alertAction in different views.

  • Just create a class with it or create a subclass of UIViewController with it that can be shared by the 4 guys? – El Tomato Jul 18 '17 at 08:48

6 Answers6

0
  1. Create BaseController with a method that can show alert.

     //Copyright © 2017 dip. All rights reserved.
    
    import UIKit
    
    class BaseController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    ///This is common method to show alert with same action 
    func showAlert() {
        let alert = UIAlertController(title: "Alert", message: "my msg on alert", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
            ///This will be common alert ok aciton for all child controllers.
            print("Do some userful common work..")
    
        }))
    
          self.present(alert, animated: true, completion: nil)            
      }
    }
    
  2. Inherit Your 4 controllers from BaseController

     //  Copyright © 2017 dip. All rights reserved.
    //
    
    import UIKit
    
    class ChildVC: BaseController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //call show alert when ever you wish 
            ///This method will call showAlert() method on super class (BaseController)
            self.showAlert()
    
        }
       }
    
    1. Call self.showAlert() method from child when you want show alert with common action.
dip
  • 3,548
  • 3
  • 24
  • 36
0

You can create UIViewController extension like below:

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

And you can use this alert in UIViewController like below:

    showAlert(title: "Your Title", message: "Your custom Message", actionTitles: ["Ok","Cancel"], actions: [{ action1 in
                   //OK Action
                }, { action2 in
                    // Cancel Action
                }
           ])

Hope will get your solution.

Jaydeep Vora
  • 6,085
  • 1
  • 22
  • 40
0

You can also use like this way.

class IOSPublicDefaultAlert: NSObject{

    var viewController: UIViewController?
    var actionCompletion: ((String) -> ())?
    var alertTitle: String?
    var alertMessage : String?
    var alertType: UIAlertControllerStyle?
    var actionTitleAndType: [String: UIAlertActionStyle]?



    init(viewController : UIViewController,alertTitle: String?,alertMessage : String?,alertType: UIAlertControllerStyle = .alert,actionTitleAndType: [String: UIAlertActionStyle] ,actionCompletion :  ((String)->())?){

        super.init()
        self.viewController = viewController
        self.actionCompletion = actionCompletion
        self.alertTitle = alertTitle
        self.alertMessage = alertMessage
        self.alertType = alertType
        self.actionTitleAndType = actionTitleAndType

        showAlert()
    }


    func showAlert(){

        let alert = UIAlertController.init(title: alertTitle, message: alertMessage, preferredStyle: self.alertType ?? .alert)

        for (actionTitle, actionType) in actionTitleAndType!{

            let action = UIAlertAction(title: actionTitle, style: actionType) { (action) in

                if let com = self.actionCompletion{

                    com(actionTitle)
                }
            }
            alert.addAction(action)
        }

        viewController?.present(alert, animated: true, completion: nil)
    }
}

and use add where you like as below sample

  _ = IOSPublicDefaultAlert.init(viewController: self, alertTitle: "Warning!!!", alertMessage: alertMessage, actionTitleAndType: ["Ok" : .destructive, "Cancel" : .default], actionCompletion: { [unowned self] (title) in
        if title == "Ok"{

        }
    })
Amrit Tiwari
  • 922
  • 7
  • 21
0

In swift, your project, you can create a new .swift file and in this file create a class:

import UIKit
import Foundation

class yourFileName {

    //Create a class function alerview
    class func displayAlert(title: String, withMessage msg: String, andbtnTitle btntitle: String, in vc: UIViewController) {
        let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: btntitle, style: UIAlertActionStyle.default, handler: nil))

        appDelegate.window?.rootViewController?.present(alert, animated: true, completion: nil)
    }
}

//and now your any ViewController.swift file or any other file in your project you can access alert following way.
class viewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        yourfilename.displayAlert(title: "Alert", withMessage msg: "my alert view display", andbtnTitle btntitle: "Ok", in vc: self) // access your alertview
    }
}

I hope it's work for you.

Anh Pham
  • 2,108
  • 9
  • 18
  • 29
Berlin
  • 2,115
  • 2
  • 16
  • 28
0
// MARK: - Alertable View

protocol AlertableView {

    // Use handler if need catch cancel alert action
    typealias CompletionHandler = (() -> Void)

    func displayAlert(with title: String, message: String, actions: [UIAlertAction]?)
    func displayAlert(with title: String, message: String, style: UIAlertControllerStyle, actions: [UIAlertAction]?, completion: CompletionHandler?)
}

extension AlertableView where Self: UIViewController {

    func displayAlert(with title: String, message: String, actions: [UIAlertAction]?) {
        self.displayAlert(with: title, message: message, style: .alert, actions: actions, completion: nil)
    }

    func displayAlert(with title: String, message: String, style: UIAlertControllerStyle, actions: [UIAlertAction]?, completion: CompletionHandler?) {

        let alertCancelAction = UIAlertAction(title: "Cancel".localized, style: .cancel) { (action) in

            guard let completion = completion else { return }
            completion()
        }

        let alertController = UIAlertController(title: title, message: message, preferredStyle: style)

        if let actions = actions {

            for action in actions {
                alertController.addAction(action)
            }

            alertController.addAction(alertCancelAction)

        } else {

            // If not any custom actions, we add OK alert button

            let alertOkAction = UIAlertAction(title: "OK".localized, style: .cancel) { (action) in

                guard let completion = completion else { return }
                completion()
            }

            alertController.addAction(alertOkAction)
        }

        self.present(alertController, animated: true, completion: nil)
    }

}
Sergey Krasiuk
  • 198
  • 2
  • 9
-1

Create a common function ,

import UIKit

class AlertClass: NSObject {

    func showAlertWithVC(_ VC : UIViewController, andMessage message: String ){
        DispatchQueue.main.async {
            let alert = UIAlertController(title: "APPLICATION_NAME", message: message , preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
            VC.present(alert, animated: true, completion: nil)
        }
    }
}

Simply call AlertClass().showAlertWithVC() where you want to show Alert.

Arpit Jain
  • 1,660
  • 12
  • 23