#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)