Ios 如何创建包含标签的可重用子类UIView?

Ios 如何创建包含标签的可重用子类UIView?,ios,objective-c,uiview,Ios,Objective C,Uiview,我试图通过对UIView子类化来创建一个可重用的3-2-1倒计时计时器。 基本上,我希望它工作的方式是,当单击开始按钮(我通过故事板在主视图控制器上创建的)时,我希望初始化并向主superview添加子视图。我让它工作-正在渲染子视图-但我似乎无法从子视图中获得要显示的标签 倒计时视图 #import "CountDownView.h" @implementation CountDownView - (id)initWithFrame:(CGRect)frame { self = [s

我试图通过对UIView子类化来创建一个可重用的3-2-1倒计时计时器。 基本上,我希望它工作的方式是,当单击开始按钮(我通过故事板在主视图控制器上创建的)时,我希望初始化并向主superview添加子视图。我让它工作-正在渲染子视图-但我似乎无法从子视图中获得要显示的标签

倒计时视图

#import "CountDownView.h"
@implementation CountDownView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self startCountdown];

    }
    return self;
}

- (void)startCountdown
{
    UILabel *countTextLabel = [[UILabel alloc] initWithFrame:self.frame];
    [countTextLabel setTextColor:[UIColor blackColor]];
    [countTextLabel setBackgroundColor:[UIColor clearColor]];
    [countTextLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];
    [self addSubview:countTextLabel];
    countTextLabel.text = @"test"; // just trying to get some dummy text to work for now.

}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code     
}


@end

那么如何将标签添加到子视图中?

注释drawRect方法并检查,您可能会得到标签。如果实现了drawRect,则会优先选择自定义绘图,而不是UI元素。@Savitha我实际上刚刚解决了这个问题。我试图使用super的框架,显然这是问题的根源。当我用
CGRectMake
替换
self.frame
时,它会工作。不知道为什么。也许我不明白什么,但你能创建属性countTextLabel并在需要的地方使用吗?你如何添加你的CountDownView?我不能让这个不工作使用您的代码,这必须是唯一的地方,它是打破。这肯定适用于您的子类<代码>CountDownView*cd=[[CountDownView alloc]initWithFrame:self.view.frame];[self.view addSubview:cd]