2016-11-20 124 views
0

我在drawRect中将UIButton添加到我的UIView笔尖中。以编程方式将子视图添加到NIB的方法

-(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被调用。我应该添加哪些方法来定制用户界面元素,还是应该创建自己的方法并调用它。

+1

覆盖'initWithFrame'和'initWithCoder'。调用一个方法在那里添加你的按钮。 – Paulw11

回答

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 . 
} 
相关问题