mra214 mra214 - 1 year ago 76
Swift Question

How would you presentViewController from subview?

Say we have a custom subview, that at some state should pop the option list for user to choose from (UIAlertController). Usually when we are in a view controller we use presentViewController method, but in this case we have no access to a parent UIViewController which holds this method. Although there's seems to be some way to get to UIViewController from subviews, it's considered against MVC design pattern. Then how would you do this?
I want to keep view controller as lean as possible and custom view self sufficient, so I wouldn't want to move this logic to view controller.
Although all your advice and suggestions are welcome and appreciated.


You can always use application rootviewController to present your alert view controller :) You dont always have to opt for your view controller's view :) rootview controller is always accessible no matter where your control is :)

Here is what you can do :)

Objective C

 AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[delegate.window.rootViewController presentViewController:your_alert_view_controller animated:YES completion:nil];


let appDelegate : AppDelegate? = UIApplication.sharedApplication().delegate as? AppDelegate
if let unwrappedAppdelegate = appDelegate {
     unwrappedAppdelegate.window!.rootViewController! .presentViewController(alert, animated: true, completion: nil)

Hope my answer helped you :)