在另一个UIViewController中调用一个函数

时间:2015-12-25 20:24:31

标签: ios swift uiviewcontroller

这个标题可能不合适,因为我不知道该怎么称呼它。

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在其他视图中将是多余的。所以我想把它移到自己的班级。

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);
    }

}

但当然,我收到错误说

  

警告:尝试出现    谁的观点不在窗口   层次!

所以根据我的理解,我猜错了,因为AlertMessageViewController没有附加到任何东西?所以我相信我可以创建另一个UIViewController,然后链接它们。但是每次我想显示一条警告信息时,它都会切换视图,而不是只弹出一个小窗口。我该怎么做?

2 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:0)

您还可以扩展UIViewController

extension UIViewController
{
    func displayAlertMessage(alertMessage: String) {

        let alert = UIAlertController("YOUR_TITLE", alertMessage, YOUR_STYLE);
        let dismissAction = UIAlertAction("YOUR_TITLE", YIUR_STYLE, YOUR_HANDLER);

        alert.addAction(dismissAction);
        self.presentViewController(alert, true, YOUR_COMPLETION:BLOCK);
    }
}

然后你可以致电myController.displayAlertMessage("This is my alert")

显然,扩展名不能包含存储的属性,所以你必须传递你需要的所有参数