Antony Chahine Antony Chahine - 1 year ago 58
iOS Question

IOS SWIFT 2 - display the same alert with different titles in different scene

i need to display the same alert with different titles in each time
so i want to create a function that takes a string and changes the title of the alert and then display this alert

my question is : where should i create this function ? and how call it from another viewControllers ?

Answer Source

You can extend UIAlertController by implementing your own custom class, then you present this controller where you want it to be presented just changing title. Below is the sample code, it works. Hope you will understand the concept.

import UIKit

extension UIAlertController {
class func alertControllerWithTitle(title: String, message: String) -> UIAlertController {
    let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    controller.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
    return controller

class ViewController: UIViewController {

let someProperty = 0
var alertTitle = ""

override func viewDidLoad() {


override func viewDidAppear(animated: Bool) {

func someMethod() {
    switch someProperty {
    case 0:
        alertTitle = "someProperty is 0"
    case 1:
        alertTitle = "someProperty is 1"
        alertTitle = "someProperty is default"

    //present alert
    let controller = UIAlertController.alertControllerWithTitle(alertTitle, message: "some message")
    presentViewController(controller, animated: true, completion: nil)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download