サブビューとして追加した後、UIButton へのアクセスに問題があります。ビューのボタンの位置を調整しようとすると、追加した最初のボタンだけで UIButton の代わりに UIView が常に取得されます。isKindOfClassを使用すると、残りはUIButtonとして返されます。これは次のようなコードスニペットです
まず、viewDidload から createTiles メソッドを呼び出してボタンをサブビューとして追加し、adustLandscapeTiles/Portrait メソッドを呼び出してデバイスの向きを検出した後、ボタンのレイアウトを調整します。
なぜそれが起こっているのかわかりませんか??
// 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];
}
}
}
}