iPhone - how to program a button to dismiss the current view

Discussion in 'iOS Programming' started by RottenApple2, Jun 30, 2010.

  1. RottenApple2 macrumors newbie

    Joined:
    Nov 4, 2009
    #1
    Hi, I've created a button that when pressed displays a subview which contains a "Back" button. I would like the current view to be dismissed when the Back button is pressed. I have tried in the following way but of course it does not work as the compiler does not recognize CurrentView which is defined inside (
    Code:
    IBAction) ShowThisView.
    Any advice on how to work around this would be highly appreciated. Also I don't know how to remove the view and therefore I am trying to hide it. Would it work with
    Code:
    [CurrentView removeFromSuperview];
    ?

    This is my code:

    Code:
    - (IBAction) ShowThisView: (id) sender {
    
    CGRect GridBackground = CGRectMake(0, 0, 320, 380);
    UIView *myView = [[UIView alloc] initWithFrame:GridBackground];
    myView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:myView];
    
    UIButton *BackButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
    BackButton.frame = CGRectMake(110.0, 360.0, 100.0, 30.0);
    [BackButton setTitle:@"Back" forState:UIControlStateNormal];
    BackButton.backgroundColor = [UIColor clearColor];
    [BackButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
    [BackButton addTarget:self action:@selector(goBack:)   forControlEvents:UIControlEventTouchUpInside];}
    
    -(void) goBack {
    //Hides the view
    [CurrentView setHidden:YES];}
     
  2. bweberapps macrumors member

    Joined:
    Jun 25, 2010
    #2
    Yes, I would use the removeFromSuperview function, and then release the view as well to avoid memory leaks.
     
  3. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #3
    First, I don't see where you add BackButton to your subview.

    Second, rather than using addSubview (and depending on your needs for this subview), you may want to look into presenting the new view modally. You can then call [self dismissModalViewControllerAnimated:YES] to, as you would expect, dismiss that modal view. Yes, you need to create another view controller but then you help keep code to control these views more appropriately separate.
     

Share This Page