4

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. in my framework.

I don't want always pass current VC in method argument, like

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:

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.

How I can get need get current VC?

DeyaEldeen
  • 10,847
  • 10
  • 42
  • 75
Artem Krachulov
  • 557
  • 6
  • 23

2 Answers2

-1

rootViewController is a good way to go. Your root VC is probably a navigation controller, so you could use something like this:

func currentVC() -> UIViewController? {
    guard let navigationController = UIApplication.sharedApplication().keyWindow?.rootViewController as? UINavigationController else { return nil }
    return navigationController.viewControllers.last
}
konrad.bajtyngier
  • 1,786
  • 12
  • 13
-1

Hi Artem and DeyaEldeen, If I am not wrong you want to access view controller on storyboard.

You can get instance of any view controller Steps

1 set storyboard id for view controller in its Custom Class Attribute.
2 In your info view class

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



I hope it help you

Avinash Jadhav
  • 491
  • 4
  • 17