Search code examples
iossubviewsuperview

ios superview and subview


I have a superview and I add a subview to make a selection. In the superview (main view) I do the following: [self.view addSubview:cityViewController.view];

In the cityView, when I have done what I need to do, I just do self.view removeFromSuperView.

The question is, from within the superview, how can I tell when the subview has removed itself.


Solution

  • There's a few ways, but honestly since the current view controller (let's call it main) is just adding the cityViewController's view, keep the handling of adding/removing the views to the current view controller, and just have the main controller call [cityViewController.view removeFromSuperView]

    This way you can execute whatever code you want when it receives this notification (be it a method that fires or a UINotification).

    -- edit for sample UINotification code --

    main.m

    ...
    //Define cityViewController as an iVar and alloc/init it
    [[UINotificationCenter defaultCenter] addObserver:self selector:@selector(didFinishView:) name:@"DidFinishView" object:nil];
    [self.view addSubview:cityViewController.view];
    ...
    
    -(void) didFinishView:(NSNotification *)notification {
        [cityViewController.view removeFromSuperView];
    }
    

    CityViewController.m

    -(IBAction) doneButtonClick:(id) sender {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"DidFinishView" object:nil];
    }