为什么我的UIButton没有显示在我的视图上?

时间:2012-07-23 08:35:18

标签: objective-c xcode uiview uibutton

我有一个使用故事板和ARC的iOS5项目。

我在故事板中有一个带有thisViewController类的视图,在那里我得到了一个较小的子视图,我将其拖入并为其提供了类ViewView。

thisView有一个自定义的drawRect函数,可以正常工作并绘制我想要的内容。 但我也想动态添加按钮,所以我将它们添加到thisView的initWithFrame方法中,如下所示:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSLog(@"This is called <3");
        UIButton *btn= [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(0, 0, 50, 50);
        btn.backgroundColor = [UIColor redColor];
        [btn setTitle:@"Play" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn]; 
        [self bringSubviewToFront:btn];   // last thing I tried, didn't work, thought z-index was to low or something
    }
    return self;
}

自NSLog显示以来,正在调用该函数,但无法找到该按钮

- 编辑 -

额外信息:

ThisView.h

@interface RadarView : UIView <CLLocationManagerDelegate>{
    CLLocation *currentLocation;
}

2 个答案:

答案 0 :(得分:0)

不要在init方法中添加SubView。 在- (void)layoutSubviews

中添加SubView
    - (void)layoutSubviews {
         [super layoutSubviews];

         if (![self viewWithTag:12345]) {
            UIButton *btn= [UIButton buttonWithType:UIButtonTypeRoundedRect];
            btn.frame = CGRectMake(0, 0, 50, 50);
            btn.tag = 12345;
            btn.backgroundColor = [UIColor redColor];
            [btn setTitle:@"Play" forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:btn]; 
         }
    }

答案 1 :(得分:0)

我发现问题是由于一些评论和聊天

在radarviewcontroller中有一个init,它触发了initwithframe,这使得NSLog显示,并且没有使用initwithcoder,所以我没有看到任何东西,这就是问题并且混淆了东西。感谢您的评论和帮助!

相关问题