UIView:layoutSubviews vs initWithFrame

Eri*_*ric 7 uiscrollview uiview ios

在子类化时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;
}
Run Code Online (Sandbox Code Playgroud)

这是通常的任务:设置视图的框架,初始化ivar,设置滚动视图,初始化UIImages,将它们放在UIImageViews中,然后将它们放置出来.

我的问题是:应该在init哪些方面完成,以及应该在哪些方面完成layoutSubviews

WDU*_*DUK 15

您的init应该使用所需的数据创建所有对象.你在init中传递给它们的任何帧理想地应该是它们的起始位置.

然后,在layoutSubviews:中,您可以更改所有元素的帧以将它们放置在应该去的位置.不应该在layoutSubviews中进行分配或初始化,只改变他们的位置,大小等......