我在我的initWithNibName:bundle:
中间添加了一个按钮,当我将按钮视图添加到self.view中时,视图在添加按钮之前开始初始化。因此,在initWithNibName:bundle:
完成之前,viewDidLoad
中的代码就会触发。在viewDidLoad
中依赖的addSubview下面有代码,会导致它崩溃/不工作,因为初始化代码还没有运行。
当我将按钮代码添加到viewDidLoad
方法中时,我也有过同样的经历。.xib中有一个UITableView,表在viewDidLoad的其余部分运行之前被初始化,并导致tableView获得错误数据。
在初始化和加载视图时,将视图添加到视图的最佳实践是什么?只是把所有的addSubViews放在返回之前?
谢谢!
下面是我的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;
}
发布于 2011-10-18 04:56:49
您应该在viewDidLoad
中添加子视图,这意味着在将主视图加载到内存中时会添加这些视图。我将保留您的initWithNibName:bundle:
调用用于自定义初始化,而不是与UI交互,因为viewDidLoad
就是为此而设计的。
对于您的tableView,您应该在viewDidLoad
中放一个调用来装入tables数据源。加载数据源后,只需在表视图上调用reloadData
,即可将数据加载到表视图中。
例如:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addSubview:saveButton];
[self loadDataSource];
}
- (void)loadDataSource {
// load datasource here
[self.tableView reloadData];
}
发布于 2011-10-18 05:02:25
对视图控制器的view属性的任何访问都会延迟初始化视图。这将触发对viewDidLoad的调用,该调用将在对视图属性的访问返回到initWithNibName:之前执行。您应该在viewDidLoad中或使用接口构建器添加子视图。
https://stackoverflow.com/questions/7799306
复制相似问题