简体   繁体   English

如何初始化从xib加载的UIView子类? 继承问题

[英]How to initialize UIView subclass that is load from xib? Problems with inheritance

Hi I created UIView subclass MightyPickerView that is loaded from xib like this.嗨,我创建了 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;
}

Until now this works great also I used this in many previous projects without any issues.到目前为止,这很好用,我在以前的许多项目中也使用过它,没有任何问题。 But now I want to create MightyPickerView's subclass called TimePickerView .但现在我想创建 MightyPickerView 的子类TimePickerView

- (instancetype)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame]; // here's the problem
  if (self) {
    [self setupSizes];
  }
  return self;
}

When I run the app it crashes当我运行应用程序时它崩溃了

[MightyPickerView setupSizes]: unrecognized selector sent to instance 0x137e53660

The problem is that this line self = [super initWithFrame:frame];问题是这一行self = [super initWithFrame:frame]; return MightyPickerView instead of TimePickerView.返回 MightyPickerView 而不是 TimePickerView。

How should I write the MightyPickerView's initializor so that it will return subclass if it needs to.我应该如何编写 MightyPickerView 的初始化程序,以便它在需要时返回子类。

What you're doing makes no sense.你在做什么毫无意义。 You should not be misusing initWithFrame to have your view turn around and load itself from a nib.您不应该滥用initWithFrame来让您的视图转向并从笔尖加载自身。 If you want to load a MightyPickerView from a nib, load it from a nib, ie have some other class say [[NSBundle mainBundle] loadNibNamed:@"MightyPickerView" owner:nil options:nil];如果你想从一个笔尖加载一个 MightyPickerView,从一个笔尖加载它,即有一些其他的类说[[NSBundle mainBundle] loadNibNamed:@"MightyPickerView" owner:nil options:nil]; and pull out the view.并拉出视图。 To encapsulate, use a class factory method, maybe.要封装,也许可以使用类工厂方法。 Do not do this sort of skanky self-substitution inside an init .不要在init进行这种卑鄙的自我替换。 It may have been apparently working but it was always wrong behavior and now it has come back to bite you.它可能显然有效,但它总是错误的行为,现在它又回来咬你了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM