2010-04-26 38 views
0

我正在嘗試爲我的表的選定行提供一個按鈕。適合iPhone的UITableView的特定行上的不顯示按鈕

這裏是我使用的示例代碼:裝載1時

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

    static NSString *ControlRowIdentifier = @"ControlRowIdentifier"; 

    UITableViewCell *cell = [tableView 
          dequeueReusableCellWithIdentifier:ControlRowIdentifier]; 

    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
             reuseIdentifier:ControlRowIdentifier] autorelease]; 
    } 

    if ([indexPath row] > 5) { 

     UIImage *buttonUpImage = [UIImage imageNamed:@"button_up.png"]; 
     UIImage *buttonDownImage = [UIImage imageNamed:@"button_down.png"]; 
     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
     button.frame = CGRectMake(0.0, 0.0, buttonUpImage.size.width, buttonUpImage.size.height); 
     [button setBackgroundImage:buttonUpImage forState:UIControlStateNormal]; 
     [button setBackgroundImage:buttonDownImage forState:UIControlStateHighlighted]; 
     [button setTitle:@"Tap" forState:UIControlStateNormal]; 
     [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; 
     cell.accessoryView = button; 

    } 

    NSUInteger row = [indexPath row]; 
    NSString *rowTitle = [list objectAtIndex:row]; 
    cell.textLabel.text = rowTitle; 

    return cell; 
} 

此代碼工作絕對沒問題。因此,根據邏輯,它顯示所有大於5的行的「點擊」按鈕。

當我向上和向下滾動時會出現問題。一旦我這樣做,它就開始把這個按鈕放在任意一行。我不明白爲什麼它會這樣做,如果有人可以提供一些提示,這將非常有幫助。

謝謝。

回答

1

問題是重複使用單元的標識符。在你的情況下,索引小於6的單元格必須帶有一個標識符,其餘的來自其他標識符。

+0

謝謝維克多!問題的確在於重新使用單元的標識符。一旦我使用了唯一標識符,問題就消失了! – user315603 2010-04-26 18:48:13

+0

唯一標識符需要具有獨特特徵的單元格,在您的情況下是帶有按鈕的單元格和沒有按鈕的單元格。如果爲每個單元生成唯一的標識符,他們將停止重用,這將影響效率 – Victor 2010-04-26 21:07:08

0

表視圖單元格是可重複使用的對象,你必須做一些乾淨的工作。嘗試使用下一個:

if ([indexPath row] > 5) { 

    ... 


} else { 
    cell.accessoryView = nil; 
} 
相關問題