简体   繁体   English

如何在非viewcontroller类中获取可见/当前viewcontroller? 迅速

[英]How get visible / current viewcontroller in non-viewcontroller class? Swift

I have information box object - "Info view". 我有信息框对象-“信息视图”。 And I wanted to append this view to current VC view, sometimes directly in VC class sometimes outside VC class, ex. 我想将此视图附加到当前的VC视图中,有时直接在VC类中,有时在VC类之外,例如。 in my framework. 在我的框架中。

I don't want always pass current VC in method argument, like 我不想总是在方法参数中传递当前的VC,例如

class InfoView: UIView {

    /* Initialization methods */

    func show(viewController: ViewController) {

       /* some code */

        viewController.addSubview(self)
    }
}

I want get current VC directly in my "Info view" class: 我想直接在我的“信息视图”类中获取当前的VC:

class InfoView: UIView {

    /* Initialization methods */

    func show() {
        let viewController = /* need get current VC */

        /* some code */

        viewController.addSubview(self)
    }
}

rootViewController property in UIApplication.sharedApplication() returns current VC, but after transitions this VC not changed. UIApplication.sharedApplication() rootViewController属性返回当前VC,但在转换后此VC不会更改。

How I can get need get current VC? 如何获得需要的最新VC?

rootViewController is a good way to go. rootViewController是一个很好的方法。 Your root VC is probably a navigation controller, so you could use something like this: 您的根VC可能是导航控制器,因此您可以使用以下代码:

func currentVC() -> UIViewController? {
    guard let navigationController = UIApplication.sharedApplication().keyWindow?.rootViewController as? UINavigationController else { return nil }
    return navigationController.viewControllers.last
}

Hi Artem and DeyaEldeen, If I am not wrong you want to access view controller on storyboard. 嗨,Artem和DeyaEldeen,如果我没有记错,您想访问情节提要上的视图控制器。

You can get instance of any view controller Steps 您可以获取任何视图控制器的实例步骤

1 set storyboard id for view controller in its Custom Class Attribute. 1在其“自定义类”属性中为视图控制器设置情节提要ID。
2 In your info view class 2在您的信息视图类中

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
MyViewcontroller *c = [storyboard instantiateViewControllerWithIdentifier:@"MyViewcontrollerStoryboardID"]



I hope it help you 希望对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM