Where to initialize custom UIView, instantiated in Interface Builder?

后端 未结 3 1769
孤街浪徒
孤街浪徒 2020-12-30 08:00

I have a subclass of UIView that\'s instantiated in a XIB file. I need it to do some initialization (settings some variables and creating a subview).

However, I do n

3条回答
  •  孤独总比滥情好
    2020-12-30 08:35

    You should use initWithFrame: when initializing views (since it's the designated initializer). Hence, if you have initWithValues: make sure you call initWithFrame: from it.

    Something like this should work for initializing: ;)

    - (void)initialize{
         //init your ivars here
    }
    
    - (id)initWithCoder:(NSCoder *)aCoder{
        if(self = [super initWithCoder:aCoder]){
            [self initialize];
        }
        return self;
    }
    
    - (id)initWithFrame:(CGRect)rect{
        if(self = [super initWithFrame:rect]){
            [self initialize];
        }
        return self;
    }
    

    I was going to add a further explanation, but mplappert's answer is clear enough. Use awakeFromNib if necessary.

提交回复
热议问题