I have problem accessing UIButton after adding it to as a subview. When i try to adjust the buttons location on the view I always get a UIView instead of UIButton only with the first button that i added. The rest return as UIButton when i use isKindOfClass. Here is a code snippet as follow
First i call createTiles method from viewDidload to add the buttons as a subviews then adjust the buttons lay out after detecting device orientation by calling adustLandscapeTiles/Portrait method.
I’m not sure why that is happening any idea ? ?
// Adding buttons to view
- (void)createTiles
{
for(int i=0;i<[self.contentList count];i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(buttonSelection:)forControlEvents:UIControlEventTouchDown];
[button setTitle:[ [contentList objectAtIndex:i] valueForKey:@"nameKey"] forState:UIControlStateNormal];
button.tag=i;
[self.view insertSubview:button atIndex:0];
NSLog(@"adding %i %@",i , [ [contentList objectAtIndex:i] valueForKey:@"nameKey"]);
[button release];
}
}
- (void)adustLandscapeTiles
{
for (int row = 0; row < Portrait_TILE_ROWS; ++row)
{
for (int col = 0; col < Portrait_TILE_COLUMNS; ++col)
{
int index = (row * Portrait_TILE_COLUMNS) + col;
CGRect frame = CGRectMake(LandScape_TILE_MARGIN + col * (LandScape_TILE_MARGIN + LandScape_TILE_WIDTH),
LandScape_TILE_MARGIN + row * (LandScape_TILE_MARGIN + LandScape_TILE_HEIGHT),
LandScape_TILE_WIDTH, LandScape_TILE_HEIGHT);
/// check subview is a button
NSLog(@"index: %i tag : %i Is of type UIButton?: %@",index,[[self.view viewWithTag:index] tag], ([ [self.view viewWithTag:index] isKindOfClass: [UIButton class]])? @"Yes" : @"No");
/// Only the first button added with tag zero return UView instead of UIButton ??
UIButton *tmb= (UIButton *)[self.view viewWithTag:index];
if([tmb isKindOfClass:[UIButton class]]) //isKindOfClass
{
[ [self.view viewWithTag:index] setFrame:frame];
}
}
}
}
While I was adding a more robust solution to your problem I noticed you are over-releasing
button. You should not call[button release]you do not own it! But that is not your only problem…If you do not assign a tag to a
UIViewit will have a tag of zero, so if your view has some other subviews that you did not assign tags to you may be getting one of them. Try adding some offset to your tags, for example:Obviously you need to add this offset when you retrieve your tiles too.
Having said this, your current method is what a more experienced programmer might call fragile if someone ever subclasses your class or even if you edit sometime later you may assign conflicting tags and cause some problems. You might consider a more robust solution.
Since what you really want to do is maintain as array of buttons that you can access by index, why not do exactly that without relying on tags?
So in your
UIViewControlleradd aNSMutableArrayto hold your buttons.