DG7
DG7

Reputation: 171

How to use custom UIAlertview in multiple ViewControllers?

I am looking for a way to call a custom alert view from multiple view controllers. So far I have made several different attempts without success.

With the first two methods, I do not get any compiling errors. The app runs fine and then crashes when I call the alert from another view controller.

Thanks in advance for any input!

EDIT:

This example works when I put it in another swift file.

public func showSimpleAlert(title: String, message: String?, presentingController: UIViewController) {

if IS_OS_8_OR_LATER() {
    let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert)

    controller.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { (action) -> Void in

    }))

    presentingController.presentViewController(controller, animated: true, completion: nil)
} else {
    let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "OK")
    alert.show()
}
}

This is the one I want to work on.

public func showAlert(oMsg: String, oTitle:String) {
    alertView.backgroundColor = UIColor.whiteColor()
    alertView.layer.cornerRadius = 25

    alertTitleLabel.text = oTitle as String
    alertTitleLabel.font = UIFont(name: "Open-Sans-Bold", size: 20)
    alertTitleLabel.textColor = UIColor.blackColor()
    alertTitleLabel.textAlignment = .Center
    alertTitleLabel.numberOfLines = 1
    alertTitleLabel.frame = CGRectMake(25, 60, 264, 112)

    alertLabel.text = oMsg as String
    alertLabel.font = UIFont(name: "Open-Sans", size: 20)
    alertLabel.textColor = UIColor.blackColor()
    alertLabel.textAlignment = .Center
    alertLabel.numberOfLines = 4
    alertLabel.frame = CGRectMake(25, 130, 264, 112)

    okButton.setTitle("OK", forState: .Normal)
    okButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    okButton.frame = CGRectMake(60, 230, 197, 75)
    okButton.addTarget(UIViewController.self, action:#selector(LoginViewController.buttonAction(_:)), forControlEvents: .TouchUpInside)

}

Upvotes: 5

Views: 5185

Answers (1)

Sibasish
Sibasish

Reputation: 356

I will give the answer for a simple custom alertview which is basically a modified uiviewcontroller. you can use a uiviewcontroller as a uialertviewcontroller as follow.

Simple AlertView::

enter image description here

The AlertVC:

import UIKit

class ErrorAlert: UIViewController {
    var titlenote:String = ""
    var message:String = ""

    @IBOutlet weak var cancelBtn: UIButton!
    @IBOutlet weak var messageHolder: UILabel!

    @IBOutlet weak var imageHolder: UIImageView!
    @IBOutlet weak var titleHolder: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor =  UIColor.black.withAlphaComponent(0.7)
        // Do any additional setup after loading the view.
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.messageHolder.text = self.message
        self.titleHolder.text = self.titlenote

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func dismiss(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }


}

This viewcontroller can be reuse in any vc and any number of times.

Useage Example::

let alertController = self.storyboard?.instantiateViewController(withIdentifier: "erroralert") as! ErrorAlert
                alertController.titlenote = "Invalid login"
                alertController.message = "Invalid facebook account."
                alertController.providesPresentationContextTransitionStyle = true
                alertController.definesPresentationContext = true
                alertController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
                alertController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
                self.present(alertController, animated: true, completion: nil)

I have made the background of the alertviewvc semitransparent by setting the alpha value.

Actual Display ::

enter image description here

You can make more complex alertview by this method but for reusability you have apply some logic as the button actions will be different for different viewcontroller. Example -- Sometime you can use the alertview for logout alert or sometime for submitting a form .So in both cases the action will be different so for reusability you have to write extra logic.

Another alertView::

enter image description here

I hope my answer will help you.:)

Upvotes: 6

Related Questions