我一直试图将我的函数从另一个类调用到我的新类中。 原始功能代码和类显示如下:
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文章,但我一直遇到同样的问题而没有显示警报。
答案 0 :(得分:1)
所以看起来这里有一些事情发生了。
logInViewController
继承自ViewController
而不是UIViewController
。如果没有,那就应该。ViewController().displayAlert(...)
正在初始化ViewController
实例,然后在该实例上调用displayAlert(...)
。初始化的ViewController
实例不在视图层次结构中,因此警报不会显示在任何位置。无论如何,你不应该打电话给ViewController()
。displayAlert(...)
调用ViewController()
,就会调用当前视图控制器的实例方法(self
),这是正确的!所以,你应该像这样或像self.displayAlert(...)
那样调用它(假设logInViewController
继承自ViewController
)。