参考连接
@interface CustomView ()
@property(nonatomic,strong)UIView *sView;
@end
@implementation CustomView
-(instancetype)init
{
self = [super init];
if (self) {
NSLog(@" %s ",__func__);
}
return self;
}
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSLog(@" %s ",__func__);
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
NSLog(@" %s ",__func__);
[self sView];
}
#pragma mark - lazy load
-(UIView *)sView
{
if (!_sView) {
_sView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 20.0f, 20.0f)];
_sView.backgroundColor = [UIColor redColor];
[self addSubview:_sView];
}
return _sView;
}
@end
- 然后分别用 init 和 initWithFrame 来实现
- init
CustomView *customView = [[CustomView alloc] init];
customView.frame = CGRectMake(20.0f, 20.0f, 100.0f, 100.0f);
customView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:customView];
-[CustomView initWithFrame:]
-[CustomView init]
-[CustomView drawRect:]
CustomView *cView = [[CustomView alloc] initWithFrame:CGRectMake(20.0f, 20.0f, 100.0f, 100.0f)];
cView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:cView];
-[CustomView initWithFrame:]
-[CustomView drawRect:]
- 通过打印可以看出 init 内部也会调用 initWithFrame ,因此创建子视图要在 initWithFrame 里面创建
网友评论