Search code examples
cocoabuttonviewsuperview

Removing buttons from a view


Is there a way to clear the view of all buttons? My code generates buttons every second, and I made a button that I want to clear them all off the screen. When I tried [brick.removeFromSuperview] (brick being the name of the button), it only deleted the last button that was produced.


Solution

  • You could keep track of the references to all your buttons in an NSMutableArray.

    e.x.

    NSMutableArray *buttons = [[NSMutableArray alloc] init];
    
    // Button creation
    UIButton *button = [[UIButton alloc] init...];
    [yourView addSubview:button];
    [buttons addObject:button];
    [button release];
    
    // Button removal
    [buttons makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [buttons removeAllObjects];  // Alternatively, you could omit this line
                                 // and recycle the buttons at a later time
    

    An advantage of this method (as opposed to just enumerating the view's subviews and looking for buttons) is that you don't have to worry about removing UIButtons from your view that shouldn't be. For example, if you don't want your "delete all buttons" button removed, just don't add it to the array.