在哪里调用[self addSubView]?

geo*_*org 6 cocoa-touch objective-c ios

我有一个自定义视图,我需要以编程方式添加几个子视图.哪个是创建和添加这些子视图的最佳位置?Apple文档说:

如果视图类管理一个或多个完整子视图,请执行以下操作:在视图的初始化序列中创建这些子视图.

这对我来说有点不清楚.我应该处理的initWithFrame,initWithCoder或别的地方?

请注意,我不是在谈论控制器,这是一个需要初始化自己的视图.

Vin*_*zzz 9

initWithFrame是您以编程方式创建UIView的方法,而initWithCoder在从XIB实例化UIView时调用该方法.

所以这一切都取决于你将如何创建包含视图.一种涵盖所有案例的方法:

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

- (id) initWithCoder:(NSCoder*)aDecoder 
{
    if ((self = [super initWithCoder:aDecoder])){
         [self setUpSubViews];//same setupv for both Methods
    }
    return self;
}

- (void) setUpSubViews
{
     //here create your subviews hierarchy
}
Run Code Online (Sandbox Code Playgroud)