Where to initialize custom UIView, instantiated in Interface Builder?

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

提交回复
热议问题