iPhone - Load a UIView from a nib file?

前端 未结 2 769
误落风尘
误落风尘 2020-12-06 21:29

I am subclassing UIView trying to load the view i have dropped in interface builder from a nib file. I get the following error on the return line:

Terminatin

相关标签:
2条回答
  • 2020-12-06 21:43

    You are doing something very strange)

    loadNibNamed:owner:options: will call initWithCoder: to instantiate your view from xib. But you are calling loadNibNamed:owner:options: from initWithCoder:. Infinite recursion?

    To load view from xib you can do the next:

    @implementation MyView
    
    + (MyView*) myView
    {
      NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil];
      return [array objectAtIndex:0]; // assume that MyView is the only object in the xib
    }
    
    @end
    
    0 讨论(0)
  • 2020-12-06 21:45

    Rather than doing self = [objects objectAtIndex:0] you should loop through the array and make sure you are getting the right object, for example:

    for (id object in objects) {
        if ([object isKindOfClass:[YourClassName class]])
            self = (YourClassName*)object;
    }   
    

    That said, I've always done this a layer up and pulled the reference right out of the UIViewController. This breaks the abstraction layer though, since the class that just wants to use the view would need to know what Nib its in:

    UIViewController *vc = [[UIViewController alloc] initWithNibName:@"MyView" bundle:nil];
    YourClassName* view = (YourClassName*)vc.view;
    [vc release];
    
    0 讨论(0)
提交回复
热议问题