Search code examples
iphonexcodeaddsubview

correct use of addSubView?


I currently don't have any problems using:

-(IBAction)products:(id)sender {
    products = [[Products alloc] initWithNibName:@"Products" bundle:nil];
    [self.view addSubview:products.view];
}

I tied this action to buttons to change my views. I'm sure this isn't correct though because the views are being stacked right? Will my application crash because of this? Know of any good sample code to switch views via IBAction?


Solution

  • If you are adding subviews that will cover the entire superview, you may consider removing an existing subview before adding a new one. You can do this by tagging views & then removing them.

    While adding a view, assign it a tag-

    products.view.tag = 1; //any number you want
    [self.view addSubview:products.view];
    

    To remove the older view, fetch it & remove it-

    UIView* subview = [self.view viewWithTag:1]; //Use the same number
    [subview removeFromSuperview];
    //now add a new view
    

    HTH,

    Akshay