如何在运行时添加UIButton [英] How to add a UIButton at runtime

查看:142
本文介绍了如何在运行时添加UIButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在运行时添加 UIButton ,但它不可见。

I am trying to add a UIButton at runtime however it is not visible. What am I doing wrong?

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        UIButton *btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        btn.frame = CGRectMake(0, 0, 100, 25);
        btn.backgroundColor = [UIColor clearColor];
        [btn setTitle:@"Play" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(buttonClick:)
        forControlEvents:UIControlEventTouchUpInside];
        btn.center = self.center;
        [self addSubview:btn];
    }
    return self;
}


推荐答案

首先,确保initWithFrame :方法被调用。如果你的视图是在一个NIB,initWithCoder:正在被调用。

First, make sure the initWithFrame: method is being called. If your view is in a Nib, initWithCoder: is being called instead.

第二,是按钮的唯一子视图(从你的代码看起来像,永远不知道)。该按钮可以隐藏在另一个子视图后面。调用bringSubviewToFront:如果你需要。

Second, is the button the only subview (from your code it looks like it is, but you never know). The button could be hidden behind another subview. Call bringSubviewToFront: if you need to.

最后,视图本身是否可见?它是否足够显示按钮?根据您的示例,如果视图宽度小于100像素,则按钮将不会显示,因为它将被视图的边界裁剪。

Finally, is the view itself visible? Is it big enough to show the button? Given your example, if the view is less than 100 pixels wide, the button won't show because it will get clipped by the view's bounds.

这篇关于如何在运行时添加UIButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆