Search code examples
iosinitializationuicollectionviewcell

Which init method for UIView will be called when using drag and drop in xib file


here is the custom collection view,and below label is the (rating view i design).
enter image description here

    - (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        [self initGrayStarView];

        [self initYellowStarView];

        [self initRatingLabel];
    }
    return self;
}

but i find that it every time the rating view didn't appear(image view and label did). then i found it's because that i didn't call the init method for rating view,so it's nil ,but why?
this is the init method.

but it never call it ,it only call the layoutSubview method.


Solution

  • Consider this sort of pattern...

    -(id)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            [self _setup];
        }
        return self;
    }
    
    -(id)initWithCoder:(NSCoder *)aCoder {
        if (self = [super initWithCoder:aCoder]) {
            [self _setup];
        }
        return self;
    }
    
    -(void)_setup {
        blah;
        blah;
        blah;
    }
    

    Try to "know what is happening" but that will get you through if you're just getting started.