当我将按钮视图添加到自我时,我在initWithNibName:bundle:
的中间添加了一个按钮。视图在添加按钮之前开始初始化。所以viewDidLoad
中的代码在initWithNibName:bundle:
完成之前就被触发了。在viewDidLoad
中依赖的addSubview下面有代码,并导致它崩溃/不工作,因为init代码没有运行。
当我将按钮代码添加到viewDidLoad
方法时,我也有同样的经历。在。xib中有一个UITableView,在viewDidLoad的其余部分运行之前,表被初始化,并导致tableView获得坏数据。
在初始化和加载视图时,向视图添加视图的最佳实践是什么?把所有addsubview放在Return之前?
谢谢!
我的initWithNibName:bundle:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nil];
[self setIoUIDebug:(IoUIDebugSelectorNames)];
if (IoUIDebug & IoUIDebugSelectorNames) {
NSLog(@"%@ - %@", [self description], NSStringFromSelector(_cmd) );
}
CGRect frame = CGRectMake(20, 521, 500, 37);
saveButton = [UIButton newButtonWithTitle:NSLocalizedStringFromTable(@"Save Animation Label",@"ScreenEditor",@"Save Animation Label")
target:self
selector:@selector(saveButtonPressedAction:)
frame:frame
image:[UIImage imageNamed:@"BlueButtonSmall.png"]
imagePressed:[UIImage imageNamed:@"BlueButtonSmallPressed.png"]
darkTextColor:NO];
[self.view addSubview:saveButton]; // <- Right here I'll hit breakpoints in other parts of viewDidLoad and cellForRowAtIndexPath, before the lined below get executed.
[saveButton setEnabled: NO];
[saveButton setUserInteractionEnabled: NO];
newAnimation = nil;
selectedSysCDAnimation = nil;
selectedIoCDTag = nil;
animationSaved = NO;
return self;
}
您应该在viewDidLoad
中添加子视图,这将意味着当主视图加载到内存中时添加视图。我会保留您的initWithNibName:bundle:
调用自定义初始化,而不是与UI交互,因为这是viewDidLoad
的设计目的。
关于你的tableView,你应该把一个调用来加载表的数据源在viewDidLoad
。一旦数据源被加载,你可以简单地在tableview上调用reloadData
将数据加载到tableview中。
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addSubview:saveButton];
[self loadDataSource];
}
- (void)loadDataSource {
// load datasource here
[self.tableView reloadData];
}
任何对视图控制器的view属性的访问都会延迟初始化视图。这将触发对viewDidLoad的调用,它将在initWithNibName:返回对视图属性的访问之前执行。你应该在viewDidLoad或使用interface builder中添加子视图。