在Swift 2.1中调用另一个类的函数

时间:2015-10-05 17:56:52

标签: ios swift swift2

我一直试图将我的函数从另一个类调用到我的新类中。 原始功能代码和类显示如下:

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)

    }
}

我正试图在这个类中调用显示警报功能,如下所示:

class logInViewController: UIViewController{

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

   or


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

}

代码运行时,它不会显示警报。但是如果我从原来的ViewController类中拖入功能块,我就可以调用

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

没有问题警报出现。不确定我做错了什么我已经阅读了其他Stack Overflow文章,但我一直遇到同样的问题而没有显示警报。

1 个答案:

答案 0 :(得分:1)

所以看起来这里有一些事情发生了。

  • 我猜测logInViewController继承自ViewController而不是UIViewController。如果没有,那就应该。
  • ViewController().displayAlert(...)正在初始化ViewController实例,然后在该实例上调用displayAlert(...)。初始化的ViewController实例不在视图层次结构中,因此警报不会显示在任何位置。无论如何,你不应该打电话给ViewController()
  • 只需在前面没有displayAlert(...)调用ViewController(),就会调用当前视图控制器的实例方法(self),这是正确的!所以,你应该像这样或像self.displayAlert(...)那样调用它(假设logInViewController继承自ViewController)。