malaki1974 malaki1974 - 21 days ago 9
iOS Question

For loop ignoring isKindOfClass for uibuttons in scrollview

I have code that creates, adds and tags unbuttons in a uiview which is itself in a uiscrollview. At a certain point I try to change (background color and image) some of the unbuttons with certain tags . The problem is if I choose the first button with tag 0 the for loop bombs out for the image change because either uiscrollview or the uiview do not have that method available. But I am trying to only target the unbuttons within the view (all synched up). If I pick any other buttons it works as expected. I could offset the tag from 0 to one instead but I want to know why my for loop does not work.

for (int i=0; i<[devicesArray count]; i++) {
NSLog(@"red %i", i);

for (UIView *subview in [uiv_ButtonsView subviews]) {
if([subview isKindOfClass:[UIButton class]]) {
int number = [[devicesArray objectAtIndex:i] intValue];
subview.alpha=1.0;
[[subview viewWithTag:number] setBackgroundColor:[UIColor redColor]];
UIButton *btttn = (UIButton *)[subview viewWithTag:number];
[btttn setBackgroundImage:nil forState:UIControlStateNormal];
}
}
}


Thanks - this is now working code:

for (int i=0; i<[devicesArray count]; i++) {
int number = [[devicesArray objectAtIndex:i] intValue];
[[uiv_Quilt viewWithTag:number] setBackgroundColor:[UIColor redColor]];
[[uiv_Quilt viewWithTag:number] setBackgroundImage:nil forState:UIControlStateNormal];
}

Answer
for (UIView *subview in [uiv_ButtonsView subviews]) {

subView is a subview of uiv_ButtonsView

if([subview isKindOfClass:[UIButton class]]) {

subView is a UIButton

[[subview viewWithTag:number] setBackgroundColor:[UIColor redColor]]; 

Hmmm. Now you're getting a subview of the UIButton, with tag 0 - this is the default tag for all views. You're in the private view hierarchy of the UIButton here, we've no idea what this is.

UIButton *btttn = (UIButton *)[subview viewWithTag:number]; 

Same again - you've told the compiler that you are getting a button back from this call, but you won't be. subView is already a button, buttons don't have other buttons as subviews.

[btttn setBackgroundImage:nil forState:UIControlStateNormal];

So this line of code won't work.

I don't see why you either do all your operations on subView, or use [uiv_ButtonsView viewWithTag:xx] to get your button. In the latter case, you will need to start your tags at 1, since all views have a default tag of 0.