以编程方式将子视图添加到NIB的方法

时间:2016-11-20 01:56:36

标签: ios objective-c uiview drawrect

我现在正在UIButton向我的UIView笔尖添加drawRect

-(void)drawRect:(CGRect)rect {
     self.button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
     [self.button setImage:[UIImage imageNamed:@"buttonImage.png"] forState:UIControlStateNormal];
     [self.button setTintColor:[UIColor whiteColor]];
     [self addSubview:self.button];
}

阅读此post后,只要修改了视图框,就会调用drawRect。我应该添加自定义UI元素的方法,还是应该创建自己的方法,然后调用它。

1 个答案:

答案 0 :(得分:1)

通常我会这样做

-(instancetype)initWithCoder:(NSCoder *)aDecoder{

    self = [super initWithCoder:aDecoder];
    if(self)
    {
        [self load] ;
    }
    return self ;
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame] ;
    if(self)
    {
       [self load] ;
    }
    return self ;
}
-(void)load{
    //add your subviews here .
}