我想知道是否有人知道为什么当您在 viewDidLoad
和 viewWillAppear
中设置 subview 的框架时,更改不会影响屏幕,但是如果您设置它在 viewDidAppear
他们做什么?
在我的情况下,我正在加载一个带有两个 TableView 的自定义 xib,然后尝试在 viewDidLoad
中将它们向下移动,以便为添加到 viewDidLoad
中的另一个 View 留出空间并不总是需要显示它。
问题是当我在 viewDidLoad
或 viewWillAppear
中设置框架时,它设置在对象上,我可以通过打印看到它,但它没有反射(reflect)在屏幕上.将我设置的框架调用移动到 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;
}
最佳答案
viewDidLoad 在类加载时调用,但是没有初始化任何 ui 元素,因此在 viewDidLoad 和 viewDidAppear 调用之间发生的初始化过程中,任何引用它们的尝试都将被覆盖或不可用。一旦所有 ui 元素都被初始化并绘制 viewDidAppear 就会被调用。
viewDidLoad - Called after the controller's view is loaded into memory
此时 View 不在 View 层次结构中。
viewWillAppear - Notifies the view controller that its view is about to be added to a view hierarchy.
同样, View 尚未添加到 View 层次结构中。
viewDidAppear - Notifies the view controller that its view was added to a view hierarchy.
只有这样, View 才会添加到 View 层次结构中。
更新
viewDidLayoutSubviews
是在 UI 真正出现在屏幕上之前修改 UI 的最合适的位置。
viewDidLayoutSubviews - Notifies the view controller that its view just laid out its subviews.
关于objective-c - 在 viewDidAppear 之前无法正确设置框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13079172/