子类化时UIView
,我通常将所有初始化和布局代码放在它的init
方法中。但有人告诉我布局代码应该通过覆盖来完成layoutSuviews
。SO上有一篇文章解释了何时调用每种方法,但我想知道如何在实践中使用它们。
我目前将所有代码都放在init
方法中,如下所示:
MyLongView.m
- (id)initWithHorizontalPlates:(int)theNumberOfPlates
{
self = [super initWithFrame:CGRectMake(0, 0, 768, 1024)];
if (self) {
// Initialization code
_numberOfPlates = theNumberOfPlates;
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.frame];
[scrollView setContentSize:CGSizeMake(self.bounds.size.width* _numberOfPlates, self.bounds.size.height)];
[self addSubview:scrollView];
for(int i = 0; i < _numberOfPlates; i++){
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"a1greatnorth_normal_%d.jpg", i+1]];
UIImageView *plateImage = [[UIImageView alloc] initWithImage:img];
[scrollView addSubview:plateImage];
plateImage.center = CGPointMake((plateImage.bounds.size.width/2) + plateImage.bounds.size.width*i, plateImage.bounds.size.height/2);
}
}
return self;
}
这是通常的任务:设置视图的框架,初始化 ivar,设置滚动视图,初始化 UIImages,将它们放在 UIImageViews 中,将它们布置出来。
我的问题是:哪些应该在 中完成init
,哪些应该在 中完成layoutSubviews
?