2013-08-03 126 views
0

我只想在viewcontoller的xib或stroy board上加載自定義視圖(使用xib)。最佳做法也是這樣做。如何使用xib或故事板上的xib加載自定義視圖

我已經在下面使用了awakeAfterUsingCoder函數代碼。

(id) awakeAfterUsingCoder:(NSCoder*)aDecoder 
{ 
    BOOL theThingThatGotLoadedWasJustAPlaceholder = ([[self subviews] count] == 0); 
    if (theThingThatGotLoadedWasJustAPlaceholder) 
    { 
     CustomView* theRealThing = (id) [CustomView view]; 
     theRealThing.frame = self.frame; 
     theRealThing.autoresizingMask = self.autoresizingMask; 
     return theRealThing; 
    } 
    return self; 
} 

但使用此功能後,我的awakeFromNib開始多次調用。

請注意。

回答

0

正如您發現的那樣,當前鏈接的正確答案過於複雜和錯誤。還有一個更規範和更好的方式來做到這一點:

  1. 創建一個空的廈門國際銀行
  2. 一個UIView添加到您的廈門國際銀行,以便它是唯一的頂層對象(除了代理急救員和文件的所有者)
  3. 更改類新的UIView到CustomView
  4. 實例化XIB和檢索CustomView例如像這樣:

    CustomView *視= [[UINib nibWithNibName:@ 「CustomView」 捆綁:無] instantiateWithOwner:self opti附件:無] [0];

  5. 將它添加到您的視圖層次在視圖控制器的viewDidLoad方法:

    [self.view addSubview:圖]

確保在您的CustomView子類中覆蓋-initWithCoder:以防您需要執行任何自定義初始化。我知道這很多,所以請讓我知道這些步驟是否會讓您感到困惑,或者您是否陷入困境。