我在想,为什么当你在viewDidLoad
和viewWillAppear
中设置子视图的框架时,更改不会在屏幕上生效,但如果你在viewDidAppear
中设置,则会生效?
就我的情况而言,我正在加载一个带有两个表视图的自定义xib,然后尝试在viewDidLoad
中将它们向下移动,以留出空间放置另一个视图。由于不必始终显示该视图,因此该视图在viewDidLoad
中添加。
问题是,当我在viewDidLoad
或viewWillAppear
中设置框架时,它被设置到对象上,我可以通过打印来看到,但它不会反映在屏幕上。将我的设置框架调用移动到viewDidAppear
中将使一切按预期工作。
在viewDidLoad
中设置框架是错误的吗?
- (id)init {
if ( self = [super initWithNibName:@"MyView" bundle:nil] ) {}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.descriptionWebView = [[[UIWebView alloc] initWithFrame:CGRectMake( 0, 0, self.view.frame.size.width, 200 )] autorelease];
[self.view addSubview:self.descriptionWebView];
self.tableView1.autoresizingMask = UIViewAutoresizingNone;
self.tableView2.autoresizingMask = UIViewAutoresizingNone;
[self.descriptionWebView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"...." withExtension:@"html"]]];
table1LocationWithHeader = CGRectMake( self.tableView1.frame.origin.x, 200, self.tableView1.frame.size.width, self.tableView1.frame.size.height - 200 );
table2LocationWithHeader = CGRectMake( self.tableView2.frame.origin.x, 200, self.tableView2.frame.size.width, self.tableView2.frame.size.height - 200 );
//this will NOT work
self.tableView1.frame = table1LocationWithHeader;
self.tableView2.frame = table2LocationWithHeader;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//this will NOT work
self.tableView1.frame = table1LocationWithHeader;
self.tableView2.frame = table2LocationWithHeader;
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
//this WILL work
self.tableView1.frame = table1LocationWithHeader;
self.tableView2.frame = table2LocationWithHeader;
}
//I added these after comments for stack overflow users, it seems like viewDidLayoutSubviews is the best place to set the frame
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
//this will NOT work
self.tableView1.frame = table1LocationWithHeader;
self.tableView2.frame = table2LocationWithHeader;
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
//this WILL work
self.tableView1.frame = table1LocationWithHeader;
self.tableView2.frame = table2LocationWithHeader;
}
[super viewDidAppear];
看起来像是复制粘贴错误。 - Maxim Kholyavkin