这个标题可能不合适,因为我不知道怎么调用它。
class OneViewController: UIViewController
{
@IBAction func someFunc(sender: AnyObject)
{
displayAlertMessage(someString)
}
func displayAlertMessage(alertMessage: String)
{
let alert = UIAlertController(title, message, preferredStyle);
let dismissAction = UIAlertAction(title, style, handler);
alert.addAction(dismissAction);
self.presentViewController(alert, animated, completion);
}
}
}
所以上面的结构可以工作,但是按照我的处理方式,displayAlertMessage 在其他 View 中将是多余的。所以我想把它移到它自己的类中。
class OneViewController: UIViewController
{
@IBAction func someFunc(sender: AnyObject)
{
AlertMessageViewController().displayAlertMessage(someString)
}
}
class AlertMessageViewController: UIViewController {
func displayAlertMessage(alertMessage: String)
{
let alert = UIAlertController(title, message, preferredStyle);
let dismissAction = UIAlertAction(title, style, handler);
alert.addAction(dismissAction);
self.presentViewController(alert, animated, completion);
}
}
当然,我收到一条错误消息
Warning: Attempt to present on whose view is not in the window hierarchy!
所以根据我的理解,我猜测错误的发生是因为 AlertMessageViewController 没有附加到任何东西?所以我相信我可以创建另一个 UIViewController,然后链接它们。但是每次我想显示一条警告消息时,它都会切换 View ,而不仅仅是弹出一个小窗口。我该怎么做?
最佳答案
class AlertMessageViewController {
static func displayAlertMessage(alertMessage: String,viewController:UIViewController) {
let alert = UIAlertController(title, message, preferredStyle);
let dismissAction = UIAlertAction(title, style, handler);
alert.addAction(dismissAction);
viewController.presentViewController(alert, animated, completion);
}
}
你可以这样调用它:
AlertMessageViewController.displayAlertMessage("message",viewController:yourControllerInstance)
关于ios - 在另一个 UIViewController 中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34466135/