change color of uitableviewcell for selected cell in sectioned table
I have sectioned table view with check selection for each secti开发者_运维知识库on(every section allows only single selection like radio button).
now what i want to do is i want to change the color of cell that user has selected(not for fraction of time color change with animation using selectedBackgroundView property of cell).
Please help.
Thanks.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
Use this code........
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor yellowColor];
}
Happy Coding....
Use this in tableview didSelectRowAtIndexPath: delegate method
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
if you want to change the selection style of a particular cell in the tableview then following code can help.. Put this in the - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
method and make the necessary changes
// x is the numbered location of that particular cell appearing in table view
if(indexPath.row==x)
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// UITableViewCellSelectionStyleBlue or UITableViewCellSelectionStyleNone
cell.selectionStyle=UITableViewCellSelectionStyleGray;
}
when the user select a row
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
gets called. You may consider implement this method in your delegate.
If you want to change only the background when it is selected you have a view reserved for that in a cell:
UIView *selectionBackground = [[UIView alloc] init];
selectionBackground.backgroundColor = A_COLOR;
myCell.selectedBackgroundView = selectionBackground;
Where A_COLOR is a UIColor. You can set this in your cellForRowAtIndexPath
.
A. If your cell's color is set to transparent (clearColor) you can simply set cell.selectedBackgroundView.backgroundColor
.
For dynamic usage this can be done in -tableView:didSelectRowAtIndexPath:
(you can change color each time user selects a row). Otherwise in -tableView:cellForRowAtIndexPath:
- either when you setup the cell (after dequeuing or creating - to allow color changes, for example, each time you call reloadData
) or when you create the table (if it wasn't dequeued - mostly for persistent color values).
B. If your cell's color is not set to transparent - set color in -tableView:didSelectRowAtIndexPath:
as mentioned in most other comments. But using this method, don't forget to restore color of previously selected row.
try this:
[cell setBackgroundColor:[UIColor colorWithRed:55.0/255.0f green:255.0/255.0f blue:178.0/255.0f alpha:1]];
精彩评论