Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 file. So, Apple told us to use designated initializer, but they are not doing it themselves - initWithCoder: doesn't call initWithFrame:. What should I do to have my designated initializer be called in both situations? Is there no way to do that?

like image 509
DemoniacDeath Avatar asked Mar 07 '13 19:03

DemoniacDeath


2 Answers

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;
}
like image 156
Rok Jarc Avatar answered Nov 12 '22 06:11

Rok Jarc


As you said:

initWithFrame: - It is recommended that you implement this method. You can also implement custom initialization methods in addition to, or instead of, this method.

initWithCoder: - Implement this method if you load your view from an Interface Builder nib file and your view requires custom initialization.

What I would do is just a method that both would call, which would have common behavior you want to implement in your UIView.

like image 42
Rui Peres Avatar answered Nov 12 '22 08:11

Rui Peres