无法在iPhone的UITableView特定行上显示按钮

时间:2010-04-26 17:24:08

标签: iphone uitableview

我正在尝试为我桌子的选定行设置一个按钮。

以下是我使用的示例代码:

- (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的“点按”按钮。

向上和向下滚动时出现问题。一旦我这样做,它就会开始将该按钮放在任意一行。我不明白为什么会这样做,如果有人可以给出一些提示,那将会非常有用。

感谢。

2 个答案:

答案 0 :(得分:1)

问题在于重用单元格的标识符。在您的情况下,索引小于6的单元格必须具有一个标识符,其余的来自其他标识符。

答案 1 :(得分:0)

表视图单元格是可重用的对象,您必须使用它进行一些干净的工作。尝试使用下一个:

if ([indexPath row] > 5) {

    ...


} else {
    cell.accessoryView = nil;
}