2012-03-13 70 views
0

我從UITableViewCell的子類中刪除UIButton時遇到了問題。僅當單元格是表格視圖中的第一個單元格時才添加此按鈕。所以碰巧這個按鈕可以是零,也可以是UIButton類的一個實例。此外,由於所有這些單元格都具有相同的標識符,因此可能會出現第一個帶按鈕的單元格移動到下方的情況。然後,我需要刪除這個按鈕。從UITableViewCell中刪除UIButton

我做它以這樣一種方式:

if(callBtn != nil) { 
    [callBtn removeFromSuperview]; 
} 

但是,它會導致應用程序崩潰。

我想這個問題可以通過對第一個單元和其他單元使用不同的標識符來解決,也許這是一個更好的解決方案。但是,我想知道這個代碼有什麼問題,或者我從UITableViewCell的子類中刪除子視圖時應該注意的。

@EDIT: 這裏是正在創建細胞的代碼:

NSString *ident = @"HistoryCell"; 
HistoryItemCell *cell = (HistoryItemCell *)[tableView dequeueReusableCellWithIdentifier:ident]; 
// If there is no reusable cell of this type, create a new one 
if (!cell) { 
    if(indexPath.row == 0) { 
     cell = [[[HistoryItemCell alloc] initWithStyle:UITableViewCellStyleDefault withCallBtn:YES reuseIdentifier:ident] autorelease]; 
    } else { 
     cell = [[[HistoryItemCell alloc] initWithStyle:UITableViewCellStyleDefault withCallBtn:NO reuseIdentifier:ident] autorelease]; 
    } 
} else { 
    if(indexPath.row != 0) { 
     [cell removeCallBtn]; 
    } 
} 

History *history = [[[Store defaultStore] allHistories] objectAtIndex:indexPath.row]; 
[cell setDataFromModel:history]; 
return cell; 

添加按鈕的代碼:

if(withCallBtn == YES) { 
     callBtn = [[UIButton alloc] initWithFrame:CGRectZero]; 
     callBtn.tag = CALL_BUTTON_TAG; 
     [callBtn addTarget:self action:@selector(callBtnAction:) forControlEvents:UIControlEventTouchUpInside]; 

     // setting background, title, etc 

     [self.contentView addSubview:callBtn]; 
     [callBtn release]; 
    } 

問候, 亞當

+1

顯示您添加按鈕的代碼。您最有可能將其過度銷燬 – 2012-03-13 22:46:50

+0

代碼位於哪裏,您標題爲「添加按鈕代碼」?那麼removeCallBtn是怎麼樣的呢? 我想你會從它的超級視圖中刪除按鈕,這會釋放它,但不要將callBtn設置爲零。您將需要執行任一操作,在從超級視圖中刪除之前保留callBtn,或者在刪除它時將變量設置爲零,並在再次使用時將其重新創建。更好地發佈完整的代碼。某處有一些邏輯錯誤。順便說一句,你不使用ARC,對吧? – 2012-03-14 00:23:47

+0

對此有何好運? – lnafziger 2012-03-23 02:42:38

回答

2

你的按鈕被保持由它的超級視圖,當你從視圖中移除它時,它將被釋放。如果要保留它,在調用removeFromSuperview之前需要保留它(否則繼續並將其設置爲零,以便在釋放後不再引用它)。

因此,我想你的代碼改成這樣:

if(callBtn != nil) { 
    [callBtn removeFromSuperview]; 
    callBtn = nil; 
} 

如果你真的想保持基準各地(這是不是你在你原來的代碼),那麼你這樣做:

if(callBtn.superview != nil) { 
    [callBtn retain]; 
    [callBtn removeFromSuperview]; 
}