2014-04-04 50 views
1

我有ReusableCellWithIdentifier的桌面我正在尋找最佳解決方案。 我不想使用removesubview方法如下面UItableVIew reusableCell在滾動後在隨機單元格中添加按鈕?

if ([cell.contentView subviews]){ 
    for (UIBUtton *subview in [cell.contentView subviews]) { 
     [subview removeFromSuperview]; 
    } 
} 

,這裏是我的cellForRowAtIndexPath方法。 我用來讓Button返回標籤屬性。但在滾動時,此按鈕被添加到diff區段的diff行中。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdetifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdetifier]; 
        if (cell == nil) 
    { 
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdetifier]; 
    } 


    if ((indexPath.section==1 && indexPath.row==0) || (indexPath.section==3 && indexPath.row==1)) { 
     cell.accessoryView = [self buttonWithMap:cell]; 

     } 
    return cell; 
} 

創建Buttonn

- (UIButton *)buttonWithMap:(UITableViewCell *)cell 
{ 

    UIButton *btn=(UIButton *)[cell.contentView viewWithTag:101]; 
    if (btn) { 
     return btn; 
    } 
    else{ 

    UIButton *btnLocation = [UIButton buttonWithType:UIButtonTypeCustom]; 
    btnLocation.backgroundColor = [UIColor clearColor]; 
    btnLocation.frame = CGRectMake(0, 0, 20, 20); 
    [btnLocation setImage:[UIImage imageNamed:@"map_location.png"] forState:UIControlStateNormal]; 
    [btnLocation addTarget:self action:@selector(setAddressBySelectLocation:) forControlEvents:UIControlEventTouchUpInside]; 
    [btnLocation setTag:101]; 
     return btnLocation; 
    } 
} 
+0

子類的UITableViewCell那麼你就可以 '復位'你的單元格在prepareForReuse: – CW0007007

+0

@ CW0007007但是這個代碼有什麼問題。爲什麼我需要子類? –

+0

@Sunnyshah當它重用一個單元格時,它仍然具有它重用的單元格的輔助視圖,因此即使您沒有替換它,也必須明確刪除舊的輔助視圖。 –

回答

1

我相信你需要將其設置爲無,當條件不滿足,否則tableView迷糊:

if ((indexPath.section==1 && indexPath.row==0) || (indexPath.section==3 && indexPath.row==1)) { 
    cell.accessoryView = [self buttonWithMap:cell]; 
}else{ 
    cell.accessoryView = nil; 
} 
+0

你的代碼適合我。但單元accessoryView僅用於特定的部分行。那麼爲什麼它採取所有行? –

+0

我知道這只是針對這兩個部分,但當它不是這些部分時,您仍然需要添加代碼,因爲單元格正在被重用 – meda

相關問題