如何在UIView的子类中覆盖initWithFrame:和initWithCoder: [英] How to override both initWithFrame: and initWithCoder: in subclass of UIView?

查看:175
本文介绍了如何在UIView的子类中覆盖initWithFrame:和initWithCoder:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将UIView子类化。我已经有了一些指定的初始化程序,我想有可能从代码或Nib文件初始化我的自定义视图。因此,Apple告诉我们使用指定的初始化程序,但是他们自己不做 - initWithCoder:不会调用 initWithFrame:。在两种情况下,如何调用指定的初始化程序,我该怎么办?有没有办法做到这一点?

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?

推荐答案

在一个方法中打包您的特殊初始化。它可以是私有的(在.m中声明)。
然后覆盖两个初始化器并从其中调用init-method。

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

这篇关于如何在UIView的子类中覆盖initWithFrame:和initWithCoder:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆