5

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.

  • I created an alert view with an interface builder that works fine on one view controller but not the other.

  • I then tried creating the alert view programmatically thinking it may have something to do with the outlets not being connected on the other view controller. This one also worked on one view controller and not the other.

  • I made a separate swift file and made a public function and the same result. With this last method, I am able to successfully re-use a regular UIAlertController on multiple view controllers but that is not exactly what I am looking for.

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)

}
Usman Maqbool
  • 3,351
  • 10
  • 31
  • 48
DG7
  • 161
  • 3
  • 15
  • 1
    It's not very clear: why doesn't the third option satisfy you ? – Coder1000 May 11 '16 at 16:00
  • not sure about what error occurs there. You can try some open projects about alert view and custom it what you want. It's better than build the new one. – truongky May 11 '16 at 16:21
  • Did you connect a delegate outlet to your custom alert view by chance in IB? – sylvanaar May 11 '16 at 16:27
  • @Coder1000 the 3rd option is the standard UIAlertController and I have a custom Alert View. I believe the reason the UIAlertController works is because of the "presentingController:UIViewController" parameter. I tried adding to my alert with no success. – DG7 May 11 '16 at 16:29
  • @DG7 Did my answer fix your issue ? – Coder1000 May 12 '16 at 10:12
  • @Coder1000 I believe it helped some but I am still working on the same problem unfortunately. I added code to elaborate my question some. I maybe am just misunderstanding the calling it with the UIAlertController part because I specifically do not want to use that. Perhaps a snippet of your explanation? – DG7 May 12 '16 at 16:00
  • @DG7 I think I found the solution. There is maybe some pseudo-code in there (just so you know) but you should understand :) – Coder1000 May 12 '16 at 18:13
  • If your problem is solved, please mark it as so. Just one side note: You should go with `UIAlertController` for newer apps. If you don't target an iOS Version before iOS 8 get rid of the old style `UIAlertView`. If you want a completely custom Alert view use `UIPresentationController`. With them you can achieve the same effect like with any AlertController - but you can layout your view like you want. – orschaef Jun 06 '16 at 11:40

1 Answers1

6

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.:)

Sibasish
  • 346
  • 3
  • 10
  • Thank you, it has been a while since I needed this, but this appears to be what I was looking for at the time. Will more thank likely use for future reference on any other iOS projects moving forward. – DG7 Feb 17 '17 at 21:08