UItableviewcell background color while click

2019-07-22 16:28发布

问题:

How to set a color to the entire cell which selected or checkmarked and reset to previous color while in unchecked in uitableview?I tried but it showing a background color for a sec.can any one please help me to code.

回答1:

Ok, here I think you want to color your cell when selected and another color if unselected,leaving those selected cells with the previous color. So have an array states globally. In didSelectRowAtIndexPath :

if (![myMutableArray containsObject:indexPath]) {
    [myMutableArray addObject:indexPath]; 
}
else{
    [myMutableArray removeObject:indexPath];
}

[sampleTableView reloadData];

And in cellForRowAtIndexPath :

if ([myMutableArray containsObject:indexPath]) {
    cell.backgroundColor = [UIColor redColor];
}
else{
    cell.backgroundColor = [UIColor greenColor];
}


回答2:

In your header file make an object of NSIndexPath(let it be checkedIndexPath used here) and assign its property and synthesize it also.In your tableView's method cellForRowAtIndexPath use:

cell.selectionStyle = UITableViewCellSelectionStyleNone;

Now in your didSelectRowAtIndexPath use following:

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

if(self.checkedIndexPath)
{
    UITableViewCell* uncheckCell = [tableView cellForRowAtIndexPath:self.checkedIndexPath];
    uncheckCell.backgroundColor = [UIColor green];
}
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
self.checkedIndexPath = indexPath;

}   

Using this you will have your cell in red if selected and in green if unselected.



回答3:

You can set the background color of the UITableViewCell

cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_normal.png"]]

and then on the click event the color will automatically change .

You can change the color of the selection by :-

cell.selectionStyle = UITableViewCellSelectionStyleBlue;

For changing the textLabel color .

cell.textLabel.textColor = [UIColor blackColor];