我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:

cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];

当前回答

override func setSelected(selected: Bool, animated: Bool) {
    // Configure the view for the selected state

    super.setSelected(selected, animated: animated)
    let selView = UIView()

    selView.backgroundColor = UIColor( red: 5/255, green: 159/255, blue:223/255, alpha: 1.0 )
    self.selectedBackgroundView = selView
}

其他回答

单元格选择的背景颜色可以通过界面构建器中的Storyboard设置:

在Swift 4中,你还可以全局设置你表格单元格的背景色(从这里取):

let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView

为所有单元格添加背景(使用Maciej的答案):

for (int section = 0; section < [self.tableView numberOfSections]; section++) {
        for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
            NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
            UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];

            //stuff to do with each cell
            UIView *bgColorView = [[UIView alloc] init];
            bgColorView.backgroundColor = [UIColor redColor];
            [cell setSelectedBackgroundView:bgColorView];
        }
    } 

我使用的是ios9.3,通过Storyboard或设置单元格设置颜色。selectionStyle不适合我,但下面的代码工作:

UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:55 / 255.0 
                                                  green:141 / 255.0 
                                                   blue:211 / 255.0 
                                                  alpha:1.0];
cell.selectedBackgroundView = customColorView;

return cell;

我找到了这个解。

我想指出的是,XIB编辑器为您提供了以下标准选项:

部分:蓝色/灰色/没有

(右边有选项的列,第4个标签,第一组“表格视图单元格”,第4个子组,3个项目中的第一个读为“选择”)

也许你想做的事情可以通过选择正确的标准选项来实现。