Where to initialize custom UIView, instantiated in Interface Builder?

后端 未结 3 1759
孤街浪徒
孤街浪徒 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:21

    Unfortunately, the above answers don't take into account these things: - (void) awakeAfterUsingCoder - and the fact it's called after anything is created by the coder (once for every Xib view). awakeFromNib suffers from the same fate, I've noticed. (The reason I found this)

    Another initializing issue is that initWithCoder and initWithFrame can be avoided for custom views. And if they are called, lazy loading (though not as important on views themselves), means you "might" be able to modify values. I believe I've done so in initWithCoder, but if you then initialize values in awakeFromNib, it's undone at least once.

    I've gone so far as to:

    - (void) awakeFromNib (or didMoveToSuperView);
    {
        BOOL called = NO;
        if(!called)
        {
        called = YES;
        }
    
    }
    

    Another method I use is to simply call the initializer needed, then call my own class or superclass-specific initializer.

    I, too, am looking for a dependable one-time place I can rely on. Until then, I hope my headaches save the next person an hour or so.

    Steve

    0 讨论(0)
  • 2020-12-30 08:27

    That depends on what you need to initialize. As soon as awakeFromNib gets called, all outlets and action connections of your view are established which is not the case in initWithCoder:. So if you need to rely on those connections, use awakeFromNib. Otherwise you can safely do all your initializing in initWithCoder:.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题