我在我的initWithNibName:bundle:
中添加了一個按鈕,當我將按鈕視圖添加到self.view時,視圖在添加按鈕之前開始初始化。因此viewDidLoad
中的代碼在initWithNibName:bundle:
完成之前發生火災。 addSubview下面的代碼依賴於viewDidLoad
中的代碼,並導致它崩潰/無法工作,因爲init代碼沒有運行。在initWithNibName中調用addSubview:導致viewDidLoad(和其他UI對象inits)在addSubview調用執行之前觸發
當我將按鈕代碼添加到viewDidLoad
方法中時,我的體驗相同。在.xib中有一個UITableView,並且在viewDidLoad的其餘部分運行之前該表會被插入,並導致tableView得到錯誤的數據。
當您啓動並加載視圖時,將視圖添加到視圖的最佳做法是什麼?只需在返回之前放置所有addSubViews?
謝謝!
這裏是我的initWithNibName:束:
- (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中有按鈕的addSubView,但在ViewDidLoad的中間,我的IB TableView正在初始化。我的ViewDidLoad在TableView被引用之前沒有設置TableView的init代碼。所以我的tableview cellForRowAtIndexPath沒有返回一個Cell,因爲ViewDidLoad中的Init代碼還沒有完成。所以我把addSubView放在ViewDidLoad的結尾處,這有所幫助,但是想知道爲什麼viewDidLoad被中斷以初始化TableView。 – scooter133