【问题标题】:Adding UIButton to subview not working将 UIButton 添加到子视图不起作用
【发布时间】:2011-12-01 15:33:44
【问题描述】:

我正在尝试将代码中的 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];

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

我的日志还显示了从 0..15 开始的按钮标签,所以我知道它们正在制作,但简单并没有添加到子视图“internview”中

真的看不出我在这里遗漏了什么或做错了什么..

【问题讨论】:

    标签: ios uibutton subview


    【解决方案1】:

    将您的代码更改为:

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

    在您的版本中:

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

    【讨论】:

    • 非常感谢。不初始化框架是我的观点。我已经设置它并且按钮出现了,但是方向错误!为什么它以纵向显示,而我的应用程序以横向模式出现,这很奇怪,来吧!图像必须以正确的方向显示...:-/
    猜你喜欢
    • 1970-01-01
    • 2011-10-04
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多