2010-09-16 102 views
1

我有一個奇怪的問題,我的UITableView ...我添加一個UIButton作爲子視圖到每個單元格,但是當任何一個單元格離開視圖發生了什麼事情,當我再次向上滾動,我可以看到UIButton某些單元格的背景圖片重疊!UITableViewCell和圖像重疊

cellForRowAtIndexPath方法我使用包含下面的代碼,這將增加該UIButton實例

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"]; 

    if (cell == nil) 
    { 

     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
             reuseIdentifier:@"MyCell"]; 

     [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; 

     UIFont *titleFont = [UIFont fontWithName:@"Arial-BoldMT" size:14.0]; 
     [[cell textLabel] setFont:titleFont]; 

     [cell autorelease]; 


    } 

    if([cell viewWithTag:indexPath.row]==nil){ 
    UIButton *buttonLeft = [UIButton buttonWithType:UIButtonTypeCustom]; 
    buttonLeft.tag=indexPath.row; 
    if ([[myArray objectAtIndex:indexPath.row] isEqualToString:@"item1"]) { 

     [buttonLeft addTarget:self action:@selector(doThat:) forControlEvents:UIControlEventTouchUpInside]; 
     [buttonLeft setBackgroundImage:[UIImage imageNamed:@"item1.png"] forState:UIControlStateNormal];  
     [buttonLeft setFrame: CGRectMake(5.0f, 6.2f, 30.0f, 30.0f)]; 


    }else{ 

     [buttonLeft addTarget:self action:@selector(doThat:) forControlEvents:UIControlEventTouchUpInside]; 
     [buttonLeft setBackgroundImage:[UIImage imageNamed:@"item2.png"] forState:UIControlStateNormal];  
     [buttonLeft setFrame: CGRectMake(5.0f, 6.2f, 30.0f, 30.0f)]; 

    } 
[cell addSubview:buttonLeft]; 
    } 


    cell.textLabel.text=[NSString stringWithFormat:@"   %@",[myArray objectAtIndex:indexPath.row]]; 
    return cell; 
} 

顯然,此代碼爲某種原因添加的UIButton顯示每次所述細胞。我希望每個按鈕子視圖只能添加一次.. 我在做什麼錯了?

非常感謝您的幫助

+0

也看到這個問題:http://stackoverflow.com/questions/1802707/detecting-which-uibutton-was-pressed-in-a-uitableview – Vladimir 2010-09-16 15:22:45

回答

4

這是因爲表格視圖爲了性能原因重複使用單元格。因此,cellForRowAtIndexPath:方法與您的一樣正確實施,返回已存在的單元格,並且只有在沒有可用的可重用單元格時纔會創建新單元格。

將所有與按鈕相關的代碼放在if (cell == nil) {}之內,以便該按鈕僅添加到「新鮮」單元中,並且它應該可以工作!

+0

好吧,這修復了重疊的問題,但不知何故圖像顯示在每個按鈕都會在單元格離開視圖後發生變化:S – 2010-09-16 15:36:50

+0

嗯..我想我沒有注意到您正在設置的標籤和圖像。你需要在if(cell == nil){}內完成所有的設置(創建按鈕實例),但是所有需要定期更新的東西 - 也就是每次重新加載一個單元格時 - 外面,你的代碼在哪裏... – Toastor 2010-09-16 16:25:40