1

我在我的 UITableView 中的索引位置 0 处动态添加单元格。所以每当我添加一个单元格时,我希望它被选中,我有一个不同的图像用于选定的状态。所以每当我添加一个单元格时,它都会被选中。现在添加几个单元格后,用户可以选择任何索引位置的任何单元格。现在,当他再次开始添加单元格时,应取消选择先前选择的单元格,并选择索引位置为零处新添加的单元格。

为此,我写了这段代码

- (void)selectRow0
{

    NSLog(@"row:%d",array.count);

    if(row > 1)
    {
        NSLog(@"indexpathoCheck%@",m_selectedCellIndexPath);
        [self tableView:m_tableView didDeselectRowAtIndexPath:m_selectedCellIndexPath];

    }

    if(row > 0)

        m_selectedCellIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [m_tableView selectRowAtIndexPath:m_selectedCellIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self tableView:m_tableView didSelectRowAtIndexPath:m_selectedCellIndexPath];

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    m_selectedCellIndexPath = indexPath;     

    TestCell *cell = (TestCell*)[tableView cellForRowAtIndexPath:indexPath];  

    cell.customImageView.image = selectedImage;

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{


        TestCell *cell = (TestCell*)[tableView cellForRowAtIndexPath:indexPath];
        [cell.customImageView.image = nil;
    }
}
4

2 回答 2

1

我认为这是因为您正在调用didSelectRowAtIndexPath:并且didDeselectRowAtIndexPath:在两个 if 块中。

尝试将这两行替换为:

[m_tableView deselectRowAtIndexPath:m_selectedCellIndexPath];

[m_tableView selectRowAtIndexPath:m_selectedCellIndexPath];
于 2013-07-29T07:43:10.427 回答
0

希望对你有帮助

- (void)setSelected:(BOOL)selected animated:(BOOL)animated; 
        // animate between regular and selected state

假设您在单击单元格时想要其他图像和具有不同颜色的文本,您可以简单地执行

 - (void)setSelected:(BOOL)selected animated:(BOOL)animated
{

      [super setSelected:selected animated:animated];
    if(selected)
        {

                self.image  =[UIImage imageNamed:@"some_image.png"];
                self.lbl.textColor=[UIColor whiteColor];

        }
    else
   {

                self.image  =[UIImage imageNamed:@"some_ another _image.png"];
                self.lbl.textColor=[UIColor grayColor];
   }

}

并将此代码添加到您的didSelectRowAtIndexPath

 UITableViewCell    *cellClicked;

 if(cellClicked)
    cellClicked.selected=NO;
    cellClicked=[tableView cellForRowAtIndexPath:indexPath];
    cellClicked.selected=YES;
于 2014-08-14T11:33:31.247 回答