ios自定义View:init和initWithFrame方法
The reason is that inside View1 initWithFrame: you call [super initWithFrame:]. UIView initWithFrame: calls [self init].
When you call a method inside a class, the method on the very subclass is called. So, when you call an instance method (e.g. init) on UIView it tries to call the init method on View1 (if it is implemented).
EDIT according to answer below: http://stackoverflow.com/a/19423494/956811
Let the view1 be an instance of View1.
The call hierarchy is:
- [view1(View1) init]
- [view1(UIView) init] (called by [super init] inside View1)
- [view1(View1) initWithFrame:CGRectZero] (called inside [view(UIView) init] )
- [view1(UIView) initWithFrame:CGRectZero] (called by [super initWithFrame] inside View1)
- ...
- NSLog(@"initWithFrame"); (prints "test1[8422:60b] initWithFrame")
- NSLog(@"init"); (called inside [view1(View1) init] ; prints "test1[8422:60b] init")
Check inheritance in OOP.
http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
http://www.techotopia.com/index.php/Objective-C_Inheritance
参考2
iOS开发-自定义控件的方式及注意
文/ForeverYoung21(简书作者)
原文链接:http://www.jianshu.com/p/7e47da62899c
著作权归作者所有,转载请联系作者获得授权。
为什么要在initWithFrame:方法而不是在init方法?
因为使用纯代码的方式创建自定义类,在以后使用的时候可能使用init方法创建,也有可能使用initWithFrame:方法创建,但是无论哪种方式,最后都会调用到initWithFrame:方法。在这个方法中创建子控件,可以保证无论哪种方式都可以成功创建。
这里有一点需要特别注意:
千万不能像下面这样自定义类,否则,如果你使用init方法初始化,那么,因为setUI方法会被调用两次,所以会加入两次UI控件。
- (instancetype)init
{
self = [super init];
if (self) {
[self setUI]; //
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setUI];//
}
return self;
}
- (void)setUI
{
UILabel* titleLabel = ({
UILabel* label = [[UILabel alloc]init];
label.text = @"风速";
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:16];
[self addSubview:label];
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(10);
make.top.mas_equalTo(10);
}];
label;
});
_titleLabel = titleLabel;
UIView* lineView = ({
UIView* view = [[UIView alloc]init];
view.backgroundColor = [UIColor whiteColor];
[self addSubview:view];
[view mas_makeConstraints:^(MASConstraintMaker *make) {
make.height.mas_equalTo(1);
make.left.mas_equalTo(10);
make.right.equalTo(self.mas_right).offset(-10);
make.centerY.equalTo(titleLabel.mas_bottom).offset(0);
// make.bottom.equalTo(titleLabel.mas_bottom).offset(1);
}];
view;
});
}