2013-04-26 78 views
0

在我的應用程序中,我加載了一個數組的tableView,並且爲每個行添加了一個UIButton作爲我的需要的子視圖。我知道,再利用細胞將有添加的按鈕因此保持這一事實看來,我已經實現像-cellForRowAtIndexPath方法如下滾動後,刪除添加到UITableViewCell的contentView的子視圖?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"surgeon"]; 
     if (!cell) { 
      cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"surgeon"]; 
     } 
     [[cell.contentView subviews] 
        makeObjectsPerformSelector:@selector(removeFromSuperview)]; 
          //before adding button to the contentView I've removed allSubViews 
     UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom]; 
     [btn setFrame:CGRectMake(142, 4, 28, 28)]; 

     [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"infoicon.png"]] forState:UIControlStateSelected]; 
     [btn setSelected:YES]; 
     [btn addTarget:self action:@selector(checkbtnClicked:) forControlEvents:UIControlEventTouchUpInside]; 
     [btn setTag:indexPath.row]; 

     if (indexPath.row==1) { 
      NSLog(@"CELL %@ CONTNTVEW %@",cell.subviews,cell.contentView.subviews); 
     } 
     [cell.contentView addSubview:btn]; 
     return cell; 
} 

我的問題是,TableView中是在第一次加載以及但是,當我滾動我添加的TableView按鈕即使刪除子視圖完成之前添加按鈕作爲子視圖幫助我得到這工作

回答

9

看來,刪除所有的細胞的內容視圖的子視圖導致細胞在設置文本時重新創建其單元格內容。我已經成功地重現該問題,並通過使用這種方法,而不是固定的:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"surgeon"]; 
    if (!cell) { 
    cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"surgeon"]; 
    } 
    for(UIView *subview in cell.contentView.subviews) 
    { 
    if([subview isKindOfClass: [UIButton class]]) 
    { 
     [subview removeFromSuperview]; 
    } 
    } 

    //before adding button to the contentView I've removed allSubViews 
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom]; 
    [btn setFrame:CGRectMake(142, 4, 28, 28)]; 

    [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"infoicon.png"]] forState:UIControlStateSelected]; 
    [btn setSelected:YES]; 
    [btn addTarget:self action:@selector(checkbtnClicked:) forControlEvents:UIControlEventTouchUpInside]; 
    [btn setTag:indexPath.row]; 

    if (indexPath.row==1) { 
    NSLog(@"CELL %@ CONTNTVEW %@",cell.subviews,cell.contentView.subviews); 
    } 
    cell.textLabel.font=[UIFont systemFontOfSize:12]; 
    [email protected]"A surgeon."; 
    [cell.contentView addSubview:btn]; 
    return cell; 
} 

重要提示:如果你打算做任何進一步的細胞自定義,你需要在環路手動刪除它們好。

+0

如果我打算啓用tableView的刪除選項我怎樣才能將它與我已添加的按鈕區分 – 2013-04-26 15:08:39

+0

您可以做許多不同的方法 - 最簡單的方法是將按鈕的標記設置爲硬編碼常量,然後將其用作識別這是否是您添加的按鈕的方式。 – 2013-04-26 15:55:33

相關問題