美文网首页
iOS 自定义View 的总结注意

iOS 自定义View 的总结注意

作者: CaptainRoy | 来源:发表于2019-07-08 10:07 被阅读0次

参考连接

  • 搜先自定义一个view
@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:]
  • initWithFrame
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 里面创建

相关文章

网友评论

      本文标题:iOS 自定义View 的总结注意

      本文链接:https://www.haomeiwen.com/subject/gbpnhctx.html