Cally Chan Cally Chan - 22 days ago 6
iOS Question

swift3 call alert function from other swift.file

I am new of swift3. Now, I am finding a way to call alert function from other swift.file

Like this:

//MainView.swift
//Call function
AlertFun.ShowAlert(title: "Title", message: "message..." )

//Another page for storing functions
//Function.swift

public class AlertFun {
class func ShowAlert(title: String, message: String ) {
let alert = UIAlertController(title: tile, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}


Problem in here...Cannot do this in this way....

self.present(alert, animated: true, completion: nil)


How can I implement it? Thanks.

Answer

Pass the viewController reference as a parameter to the showAlert function like:

//MainView.swift
//Call function
AlertFun.ShowAlert(title: "Title", message: "message...", in: self)

//Another page for storing functions
//Function.swift

public class AlertFun {
    class func ShowAlert(title: String, message: String, in vc: UIViewController) {    
        let alert = UIAlertController(title: tile, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
        vc.present(alert, animated: true, completion: nil)
    }
}
Comments