以编程方式将子视图添加到NIB的方法
问题描述:
我在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
被调用。我应该添加哪些方法来定制用户界面元素,还是应该创建自己的方法并调用它。
答
通常我不喜欢这样
-(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 .
}
覆盖'initWithFrame'和'initWithCoder'。调用一个方法在那里添加你的按钮。 – Paulw11