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

标签 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 在其他 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/

相关文章:

ios - 如何在 Objective C 中将 NSString 转换为 NSArray

string - Swift,使用字符串名称来引用变量

ios - UILabel 始终为零

objective-c - 模态视图 Controller 问题和 definesPresentationContext

ios - JSONValue 不解析 JSON 响应

ios - 如何将 UIView reshape 为菱形

ios - Xcode 5.1 - 没有可编译的架构(ONLY_ACTIVE_ARCH=YES,active arch=x86_64,VALID_ARCHS=i386)

ios - 关于swift中 "NSStringCompareOptions"struct document的一些问题

ios - UITableViewCell 中 UITextView 的奇怪行为

ios - MyViewController 是否在窗口层次结构中?