Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UIAlertController showing custom message

I have a ViewController class thats only purpose is to display an alert message with a custom message and title that is passes in through a custom init message. This is done as soon as the view appears, in viewDidLoad. My problem however is that when it comes to this view it pops up and is stuck in this view forever, instead of just putting the view over the other. I am not sure how to fix this. Here is the code for my alertVC class

import UIKit

class AlertVC: UIViewController {

  var myMessage: String?
  var myTitle: String?

  override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
  }

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


  override func viewDidAppear(animated: Bool){
    let alertController = UIAlertController(title: myTitle, message: myMessage, preferredStyle: .Alert)
    let OKAction = UIAlertAction(title: "OK", style: .Default) {
        (action: UIAlertAction) in print("Youve pressed OK Button")
    }
    alertController.addAction(OKAction)
    self.presentViewController(alertController, animated: true, completion: nil)
  }

  convenience init(title: String, message: String){
    self.init()
    self.myTitle = title
    self.myMessage = message
  }
}

This is the code for how I create an object for this and try and show it.

let alert = AlertVC(title: "Error", message: "error")
presentViewController(alert, animated: true, completion: nil)

Any help is appreciated, leave a comment if you need more info. Thanks!

like image 469
John511 Avatar asked Mar 14 '26 06:03

John511


1 Answers

Why not simply an extension?

extension UIViewController {

  func presentAlert(withTitle title: String, message : String) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
    let OKAction = UIAlertAction(title: "OK", style: .default) { action in
        print("You've pressed OK Button")
    }
    alertController.addAction(OKAction)
    self.present(alertController, animated: true, completion: nil)
  }
}

and call it with

presentAlert(withTitle: "Error", message: "error")

in any UIViewController class

like image 179
vadian Avatar answered Mar 16 '26 00:03

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!