ios – UIView:layoutSubviews vs initWithFrame

在子类化UIView时,我通常将所有初始化和布局代码放在其init方法中.但我被告知布局代码应该通过覆盖layoutSuviews来完成.在SO上有一个 post解释了每个方法何时被调用,但我想知道如何在实践中使用它们.

我目前将所有代码都放在init方法中,如下所示:

MyLongView.m

- (id)initWithHorizontalPlates:(int)theNumberOfPlates
{
    self = [super initWithFrame:CGRectMake(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中完成?

解决方法

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

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...