0

我有一个使用情节提要并开启 ARC 的 iOS5 项目。

我在情节提要中有一个带有 thisViewController 类的视图,在那里我有一个较小的子视图,我将其拖入并给它类 thisView。

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;
}
4

2 回答 2

0

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

    - (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]; 
         }
    }
于 2012-07-23T10:04:53.810 回答
0

I found what the problem was thanks to some comments and the chat

There was an init in the radarviewcontroller, which triggered initwithframe, which made the NSLog display, and the initwithcoder wasn't used so I didn't see anything, that was the problem and got stuff mixed up. Thanks for commenting and helpin!

于 2012-07-23T11:52:51.817 回答