Infinite loop when overriding initWithCoder

前端 未结 5 863
臣服心动
臣服心动 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:20

    Loading the nib causes initWithCoder to be called again, so you only want to do so if the subclass currently doesn't have any subviews.

    -(id)initWithCoder:(NSCoder *)aDecoder {
        self = [super initWithCoder:aDecoder];
        if (self) {
            if (self.subviews.count == 0) {
                UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
                UIView *subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
                subview.frame = self.bounds;
                [self addSubview:subview];
            }
        }
        return self;
    }
    

提交回复
热议问题