简体   繁体   中英

Calling a Function from another Class in Swift 2.1

I have been trying to call my function from another class into my new class. The original function code and class are displayed below:

class ViewController: UIViewController {

func displayAlert(title: String, message: String) {

        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

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

        //self.dismissViewControllerAnimated(true, completion: nil)

        })))

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

    }
}

I'm trying to call the display alert function in this class like so:

class logInViewController: UIViewController{

  var loginError = ViewController().displayAlert("error", message: "What is wrong")
       print(loginError)

   or


   ViewController().displayAlert("error", message: "What is wrong")

}

When the code runs it does not display the alert. But if I drag in the function block from the original ViewController class I can then call

displayAlert("error", message: "Some Message") 

With no issue the alert comes up. Not sure what I'm doing wrong I have read other Stack Overflow articles on this but I keep running into the same problem with no display of alert.

So it looks like there are a few things going on here.

  • I am going to guess that logInViewController inherits from ViewController instead of UIViewController . If it doesn't, it should.
  • ViewController().displayAlert(...) is initializing a ViewController instance and then calling displayAlert(...) on that instance. The initialized ViewController instance is not in the view hierarchy, so the alert will not be displayed anywhere. You should not be calling ViewController() anyway.
  • Simply calling displayAlert(...) without ViewController() in front will call the instance method of the current view controller ( self ), which is correct! So, you SHOULD be calling it like this or like self.displayAlert(...) (this assumes that logInViewController inherits from ViewController ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM