#import "TestView.h" 网络
@implementation TestView iview
-(id)initWithFrame:(CGRect)frame{ dom
self=[super initWithFrame:frame]; 布局
if (self) { 学习
NSLog(@"initWithFrame:%@",NSStringFromCGRect(frame)); 测试
} ui
return self; spa
} orm
//重写layoutSubviews方法 开发
-(void)layoutSubviews{
NSLog(@"layoutSunView %@", self);
[super layoutSubviews];
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self testX];
}
-(void)test21{
TestView *test = [[TestView alloc] init];
[self.view addSubview:test];
}
测试代码test22-(void)test22{
TestView *test = [[TestView alloc] init];
test.frame = CGRectMake(0, 0, 100, 100);
[self.view addSubview:test];
}
-(void)test3{
_largeView = [[TestView alloc] init];
_largeView.frame = CGRectMake(0, 0, 50, 50);
[_largeView setBackgroundColor:[UIColor greenColor]];
[self.view addSubview:_largeView];
_timer = [NSTimer scheduledTimerWithTimeInterval:1.f
target:self
selector:@selector(timerEventX:)
userInfo:nil
repeats:YES];
}
timerEvent1:- (void)timerEvent1:(id)sender
{
_smallView.frame = CGRectMake(arc4random()%100 + 20,
arc4random()%100 + 20,
arc4random()%100 + 20,
arc4random()%100 + 20);
}
timerEvent2:- (void)timerEvent2:(id)sender
{
_smallView.frame = CGRectMake(0,
0,
arc4random()%100 + 20,
arc4random()%100 + 20);
}
结果:frame的oringal不变,width,height变化,方法layoutSubviews被调用
timerEvent3:- (void)timerEvent3:(id)sender
{
_smallView.frame = CGRectMake(arc4random()%100 + 20,
arc4random()%100 + 20
50,
50);
}
结果:frame的oringal变化,width,height不变,方法layoutSubviews不被调用
对于测试如何了解layoutSubviews调用时机,能够较好掌握uiview显示的机理,有利于测试过程
好这里总结下
一、init初始化不会触发layoutSubviews
二、addSubview会触发layoutSubviews(但frame!={0,0,0,0})
三、设置view的Frame会触发layoutSubviews,前提是frame的值设置先后发生了变化(view的with,height发现变化才会触发layoutSubviews,original. x ,original. y变化不会触发layoutSubviews)