简体   繁体   中英

UItableviewcell background color while click

我如何尝试在uitableview中未选中的情况下为选中或选中的整个单元格设置颜色并重置为以前的颜色?我试过了,但它显示了背景颜色一秒钟。任何人都可以帮我编码。

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];
}

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM