[英]How to initialize UIView subclass that is load from xib? Problems with inheritance
嗨,我创建了 UIView 子类 MightyPickerView,它是从这样的 xib 加载的。
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"MightyPickerView" owner:self options:nil];
if ([arrayOfViews count] < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[MightyPickerView class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
到目前为止,这很好用,我在以前的许多项目中也使用过它,没有任何问题。 但现在我想创建 MightyPickerView 的子类TimePickerView
。
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame]; // here's the problem
if (self) {
[self setupSizes];
}
return self;
}
当我运行应用程序时它崩溃了
[MightyPickerView setupSizes]: unrecognized selector sent to instance 0x137e53660
问题是这一行self = [super initWithFrame:frame];
返回 MightyPickerView 而不是 TimePickerView。
我应该如何编写 MightyPickerView 的初始化程序,以便它在需要时返回子类。
你在做什么毫无意义。 您不应该滥用initWithFrame
来让您的视图转向并从笔尖加载自身。 如果你想从一个笔尖加载一个 MightyPickerView,从一个笔尖加载它,即有一些其他的类说[[NSBundle mainBundle] loadNibNamed:@"MightyPickerView" owner:nil options:nil];
并拉出视图。 要封装,也许可以使用类工厂方法。 不要在init
进行这种卑鄙的自我替换。 它可能显然有效,但它总是错误的行为,现在它又回来咬你了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.