将 UIButton 添加为子视图后,我无法访问它。当我尝试调整视图上的按钮位置时,我总是得到一个 UIView 而不是 UIButton 只有我添加的第一个按钮。当我使用 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];
}
}
}
}