1. 程式人生 > >正確的載入xib檔案的View或者ViewController

正確的載入xib檔案的View或者ViewController

載入的程式碼:

ViewC *vc = [[ViewCalloc] initWithNibName:

 @"ViewC"bundle:[NSBundlemainBundle]];

 [self.navigationControllerpushViewController:vc animated:YES];

編譯器爆出這樣的錯誤:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "View" nib but the view outlet was not set.'

沒有做nib檔案到xxxViewControler程式的關聯

1, 開啟nib檔案

2, 點選"File's Owner", 按command+4,設定Class為xxxViewControler

3, 按Control+"Files's Owner", 裡面有個預設的IBOutlet變數view, 看一下後面有沒有做關聯,如果沒有就拉到下面的View和檢視做個關聯

但關聯過後會爆出下面的錯誤:

*** Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'A view can only be associated with at most one view controller at a time! View <UIView: 0x7ff1d1522cd0; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x7ff1d153f150>> is associated with <ViewC: 0x7ff1d154c060>. Clear this association before associating this view with <ViewC: 0x7ff1d1544dc0>.'

經過一番折騰,自己在不知不覺中找到了解決的方法:

原來不需要對xib檔案進行修改,是載入方法的問題,直接使用下面的載入方法便可

ViewC *vc = [[NSBundlemainBundle] loadNibNamed:

    @"View" owner:niloptions:nil ].lastObject;

[self.navigationControllerpushViewController:vc animated:YES];