RomanHouse
RomanHouse

Reputation: 2552

removeFromSuperview removes all subviews

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    NSLog(@"will rotation");

    for (UIButton *button in self.view.subviews) {
        [button removeFromSuperview];
    }

}

I have a problem with this code. I need to remove only UIButtons from my view. But this code also remove all subviews of my self.view. How can I solve this?

Upvotes: 2

Views: 1726

Answers (5)

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

Do this:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
NSLog(@"will rotation");

   for (id subview in self.view.subviews) {
    if([subview isKindOfClass:[UIButton class]]) //remove only buttons
    {
      [subview removeFromSuperview];
    }
   }

}

Upvotes: 5

Chris Trahey
Chris Trahey

Reputation: 18290

self.view.subviews will fetch all subviews, and using the type UIButton * in that way does not filter the list, it just hints to the compiler that you expect to be able to treat the objects like UIButtons. You must inspect each one, like this:

for (UIView *subview in self.view.subviews) {
    if([subview isKinfOfClass:[UIButton class]])
      [subview removeFromSuperview];
}

Upvotes: 2

Elmo
Elmo

Reputation: 407

One option is to create a tag at the top of the file

#define BUTTONSTODELETE 123

and then set each of the buttons.tag = BUTTONSTODELETE

Finally :

for (UIButton *v in [self.view subviews]){
        if (v.tag == BUTTONSTODELETE) {
            [v removeFromSuperview];

Guarantees only items with that tag will be removed

EDIT: Maulik and fbernardo have a better, less messy way

Upvotes: 0

fbernardo
fbernardo

Reputation: 10104

You are iterating all the views and casting them to UIButton, not iterating UIButtons. Try this:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    NSLog(@"will rotation");

    for (UIView *button in self.view.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            [button removeFromSuperview];
        }        
    }
}

Upvotes: 4

Maulik
Maulik

Reputation: 19418

for (id button in self.view.subviews) 
    {
        if(button isKindOfClass:[UIButton class])
        {
          [button removeFromSuperview];
        }
    }

Upvotes: 3

Related Questions