UIView的drawRect和layoutSubviews方法

注意三点:

1、两个方法都是异步执行的

2、使用init初始化UIView两个方法都不会调用,所以在init中最好是初始化数据,而在上述两个方法中初始化视图

3、最好使用drawRect初始化视图,layoutSubviews在继承UIScrollView或UITableView等情况下,会调用两次


MyView.h

@interface MyView : UIView
@end

MyView.m

#import "MyView.h"

@implementation MyView
- (instancetype)init
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
    return [super init];
}
- (instancetype)initWithFrame:(CGRect)frame
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
    return [super initWithFrame:frame];
}
- (void)drawRect:(CGRect)rect {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}
- (void)layoutSubviews {
   NSLog(@"%@", NSStringFromSelector(_cmd));
}
@end

打印结果是:

2015-06-09 19:45:00.919 ViewDemo[5621:283667] initWithFrame:
2015-06-09 19:45:00.924 ViewDemo[5621:283667] layoutSubviews
2015-06-09 19:45:00.924 ViewDemo[5621:283667] drawRect:

如果把 MyView.h换成

@interface MyView : UIScrollView
@end

打印结果是:

2015-06-09 19:50:50.499 ViewDemo[5642:289117] initWithFrame:
2015-06-09 19:50:50.513 ViewDemo[5642:289117] layoutSubviews
2015-06-09 19:50:50.513 ViewDemo[5642:289117] layoutSubviews
2015-06-09 19:50:50.513 ViewDemo[5642:289117] drawRect:

可以看出layoutSubviews会打印两次,再MyView继承UILabel、UIButton、UITableView和UICollectionView等等情况下,都会调用两次。


你可能感兴趣的:(UIView的drawRect和layoutSubviews方法)