【发布时间】:2011-10-17 20:39:33
【问题描述】:
我在initWithNibName:bundle: 的中间添加了一个按钮,当我将按钮视图添加到 self.view 时,视图在添加按钮之前开始初始化。因此,viewDidLoad 中的代码会在 initWithNibName:bundle: 完成之前触发。在 viewDidLoad 中依赖的 addSubview 下方有代码,并导致它崩溃/无法工作,因为初始化代码尚未运行。
当我将按钮代码添加到viewDidLoad 方法时,我也有同样的经历。 .xib 中有一个 UITableView,并且该表在 viewDidLoad 的其余部分运行之前被初始化并导致 tableView 获取错误数据。
在初始化和加载视图时向视图添加视图的最佳做法是什么?只是把所有的 addSubViews 放在 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;
}
【问题讨论】:
标签: objective-c init viewdidload addsubview