Reputation: 2552
- (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
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
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
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
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
Reputation: 19418
for (id button in self.view.subviews)
{
if(button isKindOfClass:[UIButton class])
{
[button removeFromSuperview];
}
}
Upvotes: 3