添加UIButton到子视图不起作用

时间:2011-12-01 15:33:44

标签: ios uibutton subview

我正在尝试在代码中添加16个UIButton到我的主视图的子视图中:

internView = [[UIView alloc] initWithFrame:CGRectMake(16, 16, (self.view.frame.size.width - 16), (self.view.frame.size.height - 16) - 60)];
internView.backgroundColor = [UIColor whiteColor];


for (int rij = 0; rij < 4; rij++) //4 rows
{
    for (int kolom = 0; kolom < 4; kolom++) //4 colomns
    {

        CGFloat x = (((width + spacing) * kolom) + spacing);
        CGFloat y = (((height + spacing) * rij) + spacing);
        int tag = ((4 * rij) + kolom);


        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];

        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor blackColor];

        [button setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[projects objectAtIndex:tag]thumbnailImage]]]] forState:UIControlStateNormal];

        [button addTarget:self action:@selector(getDetail:) forControlEvents:UIControlStateNormal];

        button.tag = tag;

        NSLog(@"%i",button.tag);

        [internView addSubview:button];

    }
}

[self.view addSubview:internView];

子视图“内部视图”在主视图中可见(因为我将其设为白色背景),但按钮不可见。

此外,我的日志显示按钮的标签,从0..15开始,所以我知道它们正在制作但很简单没有添加到子视图'internview'

无法真正看到我在这里错过或做错了什么..

1 个答案:

答案 0 :(得分:7)

将您的代码更改为:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(x, y, width, height);

在您的版本中,您有:

  1. 内存泄漏,因为您已经创建了两次按钮
  2. [UIButton buttonWithType:UIButtonTypeCustom];返回新按钮 使用CGRectZero框架