我在我的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;
}
}
答案 0 :(得分:1)
我认为这是因为您在两个if块中调用了didSelectRowAtIndexPath:
和didDeselectRowAtIndexPath:
。
尝试用以下代码替换这两行:
[m_tableView deselectRowAtIndexPath:m_selectedCellIndexPath];
和
[m_tableView selectRowAtIndexPath:m_selectedCellIndexPath];
答案 1 :(得分: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;