2015-10-05 50 views
0

我一直在尝试从另一个类调用我的函数到我的新类中。 原先的功能代码和类显示如下:在Swift中调用另一个类的函数2.1

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") 

在没有发出警报大作。不知道我在做什么错我已经阅读了其他堆栈溢出文章,但我仍然遇到同样的问题,没有显示警报。

+0

我很惊讶你没有得到一个“视图不在窗口层次结构”错误信息作为线索。 –

回答

2

所以看起来这里有几件事情正在进行。

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

甜甜的男人感谢不能相信我错过了那个小细节。但那通常会发生什么,它总是有助于拥有另一双眼睛。再次感谢 – Rico

相关问题