Search code examples
iphoneibaction

Removing UIView from back/done button


I have a small app that from the home screen has a few buttons, when clicked these buttons load in a new view, this all works fine:

- (IBAction)showMaps:(id)sender {    

    MapViewController *viewcontroller = [[MapViewController alloc] initWithNibName:@"MapView" bundle:nil];
    [[self view] addSubview:viewcontroller.view];

    [viewcontroller release];

}

The problem comes when the MapView is loaded I have created a new IBAction in the MapViewController.h file:

- (IBAction)showHome:(id)sender;

And also this action within the MapViewController.m file:

- (IBAction)showHome:(id)sender {
    [self.view removeFromSuperview];

}

But no joy, bit of a newbie to this so any help more than welcome!


Solution

  • Your showMaps: method creates a view controller, but does not retain it. You will need to retain ownership of that viewController if you want it to stick around. I would suggest adding a property on your main view controller - the one that contains the showMaps: method. Example code below:

    MainViewController.h

    @interface MainViewController : UIViewController {
        MapViewController * mapViewController;
    }
    @property (nonatomic, retain) MapViewController * mapViewController;
    - (IBAction)showMaps:(id)sender;
    @end
    

    MainViewController.m

    @implementation MainViewController
    
    @synthesize mapViewController;
    
    - (void)dealloc {
        [mapViewController release];
        [super dealloc];
    }
    
    - (IBAction)showMaps:(id)sender {
        self.mapViewController = [[[MapViewController alloc]
                                  initWithNibName:@"MapView"
                                           bundle:nil] autorelease];
        [[self view] addSubview:mapViewController.view];
    }
    
    @end