2011-10-17 35 views
2

我在我的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; 
} 

回答

4

您應該添加內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]; 

} 
+0

我原本是遇到類似的問題,雖然縮小到相同的事情。我在ViewDidLoad中有按鈕的addSubView,但在ViewDidLoad的中間,我的IB TableView正在初始化。我的ViewDidLoad在TableView被引用之前沒有設置TableView的init代碼。所以我的tableview cellForRowAtIndexPath沒有返回一個Cell,因爲ViewDidLoad中的Init代碼還沒有完成。所以我把addSubView放在ViewDidLoad的結尾處,這有所幫助,但是想知道爲什麼viewDidLoad被中斷以初始化TableView。 – scooter133

0

任何訪問該視圖控制器將懶惰地初始化視圖的視圖屬性。這將觸發對viewDidLoad的調用,viewDidLoad將在initWithNibName:中訪問視圖屬性之前執行。您應該在viewDidLoad中添加子視圖或使用界面構建器。

相關問題