2010-05-19 36 views
0

我有這兩段代碼。第一個完美的作品:iPhone:[子視圖發佈]從顯示中刪除我的子視圖

UIView *tmp = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 60.0f, 296.0f, 44.0f)]; 
[self.dynamicView addSubview:tmp]; 
[tmp release]; 

第二個是幾乎相同,但視圖不顯示。

CommentBox *commentBox = [[CommentBox alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 296.0f, 44.0f)]; 
[self.dynamicView addSubview:commentBox]; 
[commentBox release]; // Why does this remove the view? 

如果我刪除了[commentBox release],則視圖出人意料地出現。但是我沒有看到這兩個代碼片段有所不同。

爲CommentBox初始化看起來是這樣的:

- (id)initWithFrame:(CGRect)frame { 
    if ((self = [super initWithFrame:frame])) { 
     // Load the nib: 
     NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil]; 
     self = [nibObjects objectAtIndex:0]; 

    } 
    return self; 
} 

回答

2

你在做-initWithFrame:奇怪的事情。我不是100%確定它是否會導致您報告的問題,但我確定它是:

  • 錯;和
  • 導致內存泄漏。

我不認爲用-init…方法中的筆尖從一個筆尖中取出存檔對象是一個好主意。可以從控制器類加載筆尖,或讓您的初始化程序從nib加載對象的子視圖而不替換self

+0

謝謝格雷厄姆。下面我發佈了我的新解決方案。 – znq 2010-05-19 10:13:03

3

思考格雷厄姆的回答後,我想出了以下解決方案:

  1. 我拖到一個新的UIView( - >可以稱之爲子的UIView)在我的主要的UIView在Interface Builder
  2. 我給這個子的UIView正確的大小(因爲我無法調整的主要UIView的,這始終是320x460)
  3. 我拖累了該子的UIView我的所有其他元素(讓所有的元素都貼在我子的UIView)
  4. 我給我sub UIView一個標籤號(Interface Builder - > View Attribut es),例如「300」
  5. 在代碼我現在做我-initWithFrame:

    的NSArray內的下列* nibObjects = [[一個NSBundle mainBundle] loadNibNamed:@ 「CommentBox」 老闆:自我選擇:無]。 UIView * subView = [[nibObjects objectAtIndex:0] viewWithTag:300]; [self addSubview:subView];

希望有所幫助。


更新:

我不得不這樣做的另一個想法。您也可以在類別CommentBox中創建一個IBOutlet UIView *viewHolder,並在IB中設置出口,而不是標籤號碼。然後在initWithFrame:我做以下事情:

[[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil]; 
[self addSubview:self.viewHolder];