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

查看:19
本文介绍了如何在 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 方法.

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天全站免登陆