Get to UIViewController from UIView?

前端 未结 29 2098
一整个雨季
一整个雨季 2020-11-22 16:57

Is there a built-in way to get from a UIView to its UIViewController? I know you can get from UIViewController to its UIView

29条回答
  •  野性不改
    2020-11-22 17:46

    Don't forget that you can get access to the root view controller for the window that the view is a subview of. From there, if you are e.g. using a navigation view controller and want to push a new view onto it:

        [[[[self window] rootViewController] navigationController] pushViewController:newController animated:YES];
    

    You will need to set up the rootViewController property of the window properly first, however. Do this when you first create the controller e.g. in your app delegate:

    -(void) applicationDidFinishLaunching:(UIApplication *)application {
        window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        RootViewController *controller = [[YourRootViewController] alloc] init];
        [window setRootViewController: controller];
        navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
        [controller release];
        [window addSubview:[[self navigationController] view]];
        [window makeKeyAndVisible];
    }
    

提交回复
热议问题