在哪里初始化自定义UIView,在Interface Builder中实例化? [英] Where to initialize custom UIView, instantiated in Interface Builder?

查看:96
本文介绍了在哪里初始化自定义UIView,在Interface Builder中实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UIView的子类,它在XIB文件中实例化。我需要它做一些初始化(设置一些变量和创建一个子视图)。

I have a subclass of UIView that's instantiated in a XIB file. I need it to do some initialization (settings some variables and creating a subview).

但是,我不总是通过Interface Builder实例化这个视图。我也是程序化。在这两种情况下,初始化需要相同。

However, I do not always instantiate this view via Interface Builder. I do it programmatically too. In both cases, the initialization needs to be the same.

我指定的初始化程序是 initWithValues:

My designated initializer is initWithValues:.

问题是; 我在哪里执行初始化?

由于我必须在两个不同的位置执行,我想我需要在一个单独的 initialize 方法(或类似的方法),并从 initWithValues:调用

Since I have to perform it in 2 different locations, I figured I need to refactor it in a separate initialize method (or something like that), and call it from initWithValues:.

但是从IB加载时,会调用 initWithCoder: awakeFromNib 从哪个方法,我必须调用 initialize ?或者我必须从 initWithCoder:调用 initWithValues:,并且在 awakeFromNib

But when loading from IB, both initWithCoder: and awakeFromNib are called. From which method do I have to call initialize? Or do I have to call initWithValues: from initWithCoder: and do nothing in awakeFromNib?

推荐答案

您应该使用 initWithFrame:初始化视图(因为它是指定的初始化程序)。因此,如果你有 initWithValues:,请确保从它调用 initWithFrame:

You should use initWithFrame: when initializing views (since it's the designated initializer). Hence, if you have initWithValues: make sure you call initWithFrame: from it.

这样应该可以初始化:;)

Something like this should work for initializing: ;)

- (void)initialize{
     //init your ivars here
}

- (id)initWithCoder:(NSCoder *)aCoder{
    if(self = [super initWithCoder:aCoder]){
        [self initialize];
    }
    return self;
}

- (id)initWithFrame:(CGRect)rect{
    if(self = [super initWithFrame:rect]){
        [self initialize];
    }
    return self;
}



我将要添加一个进一步的解释,但mplappert的答案很清楚。如有必要,使用 awakeFromNib

这篇关于在哪里初始化自定义UIView,在Interface Builder中实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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