init 和 initWithFrame 区别

当我们去自定义一些控件时 可以重写:

- (instancetype)init;

也可以去重写:

(instancetype)initWithFrame:(CGRect)frame

下面关于这两个的差异:

#import "BFView.h"

@implementation BFView

- (instancetype)init{
    
   self = [super init];
    
    NSLog(@"init:%@",NSStringFromCGRect(self.frame));
    
    return self;
    
}

- (instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    
    NSLog(@"initWithFrame:%@",NSStringFromCGRect(self.frame));
    
    return self;
}
#import "ViewController.h"
#import "BFView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    
    BFView *bfv = [[BFView alloc]init];
    
    BFView *bfv2 = [[BFView alloc]initWithFrame:CGRectMake(3, 4, 5, 6)];

}



@end

综上所述:

实现init这个方法咱们会先去调用initWithFarme这个方法 并且frame的所有值都为0;

实现iniwithFrame 这个方法 在初始化的时候 就已经把frame设置好了 并且不会去调用init这个方法

原文地址:https://www.cnblogs.com/zhubaofeng/p/5299557.html