Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...