Infinite loop when overriding initWithCoder

前端 未结 5 872
臣服心动
臣服心动 2020-12-28 08:54

I have a UIViewController with some controllers and some views. Two of these views (Grid Cell) are other nibs. I\'ve got outlets from the Grid Cells to File\'s

5条回答
  •  臣服心动
    2020-12-28 09:31

    Loading a nib will cause the corresponding owner in a

      -(id) initWithCoder:(NSCoder *) coder;  
    

    call

    Therefore your coude in this method:

    self = [[[NSBundle mainBundle] loadNibNamed: @"GridCell"
    owner: self
    options: nil] objectAtIndex:0];
    

    will cause again a call of the initWithCoder method. That's because you try to load the nib again. If you define a custom UIView and create a nib file to lay out its subviews you can't just add a UIView to another nib file, change the class name in IB to your custom class and expect the nib loading system to figure it out. What you could do is the following:

    Your custom view's nib file needs to have the 'File's owner' class set to your custom view class and you need to have an outlet in your custom class called 'toplevelSubView' connected to a view in your custom view nib file that is acting as a container for all the subviews. Add additional outlets to your view class and connect up the subviews to 'File's owner' (your custom UIView). (See https://stackoverflow.com/a/7589220/925622)

    EDIT Okay, to answer your edited question I would do the following:

    Go to the nib file where you want to include the custom view with it's nib file layouting it. Do not make it to the custom view (GridCell) itself, instead make a view which will contain your grid cell (gridCellContainer for example, but it should be a UIView) Customize the initWithFrame method within your custom view like you did in initWithCoder:

    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"GridCell" owner:self options:nil];    
            self = [nib objectAtIndex:0];
            self.frame = frame;
        }
        return self;
    }
    

    And then, in the viewController which is the fileOwner for the view where you want to include your custom view (the one with the gridCellContainer view) do this in viewDidLoad e.g.

    //...
    GridCell *gridCell = [[GridCell alloc] initWithFrame:self.viewGridCellContainer.bounds];
    [self.viewGridCellContainer addSubview:gridCell];
    

    Now eveything should work as you expected

提交回复
热议问题