UITableView Cell selected Color?
I have created a custom UITableViewCell
. The table view is showing data fine. What I am stuck in is when user touches cell of tableview, then I want to show the background color of the cell other than the default [blue color] values for highlighting the selection of cell. I use this code but nothing happens:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
I think you were on the right track, but according to the class definition for selectedBackgroundView
:
The default is nil for cells in plain-style tables (UITableViewStylePlain) and non-nil for section-group tables UITableViewStyleGrouped).
Therefore, if you're using a plain-style table, then you'll need to alloc-init a new UIView
having your desired background colour and then assign it to selectedBackgroundView
.
Alternatively, you could use:
cell.selectionStyle = UITableViewCellSelectionStyleGray;
if all you wanted was a gray background when the cell is selected. Hope this helps.
No need for custom cells. If you only want to change the selected color of the cell, you can do this:
Objective-C:
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
Swift:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.redColor()
cell.selectedBackgroundView = bgColorView
Swift 3:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
Edit: Updated for ARC
Edit: Adds Swift 3
If you have a grouped table with just one cell per section, just add this extra line to the code: bgColorView.layer.cornerRadius = 10;
UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
bgColorView.layer.cornerRadius = 10;
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release];
Don't forget to import QuartzCore.
链接地址: http://www.djcxy.com/p/49398.html上一篇: UITableView didSelectRowAtIndexPath:在第一次点击时不被调用
下一篇: UITableView单元格选择颜色?