How to override both initWithFrame: and initWithCoder: in subclass of UIView?

后端 未结 2 1686
梦如初夏
梦如初夏 2020-12-14 16:14

I\'m trying to subclass UIView. I already have some designated initializer and I want to have possibility for my custom view to be initialized either from code or from Nib f

2条回答
  •  误落风尘
    2020-12-14 17:01

    Pack your special initialization in one method. It can be private (declared in .m). Then override both initializers and call your init-method from within them.

    - (void)myInitialization
    {
        //do your stuff
    }
    
    -  (id)initWithFrame:(CGRect)aRect
    {
        self = [super initWithFrame:aRect];
    
        if (self)
        {
            [self myInitialization];
        }
    
        return self;
    }
    
    - (id)initWithCoder:(NSCoder*)aDecoder 
    {
        self = [super initWithCoder:aDecoder];
        if (self)
        {
            [self myInitialization];
        }
    
        return self;
    }
    

提交回复
热议问题