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

cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];

当前回答

对于那些只想摆脱默认选择灰色背景的人,把这行代码放在你的cellForRowAtIndexPath func中:

yourCell.selectionStyle = .None

其他回答

I've got a slightly different approach than everyone else that reflects the selection on touch rather than after being selected. I have a subclassed UITableViewCell. All you have to do is set the background color in the touch events, which simulates selection on touch, and then set the background color in the setSelected function. Setting the background color in the selSelected function allows for deselecting the cell. Make sure to pass the touch event to the super, otherwise the cell won't actually act as if its selected.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.backgroundColor = UIColor(white: 0.0, alpha: 0.1)
    super.touchesBegan(touches, withEvent: event)
}

override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
    self.backgroundColor = UIColor.clearColor()
    super.touchesCancelled(touches, withEvent: event)
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
    self.backgroundColor = selected ? UIColor(white: 0.0, alpha: 0.1) : UIColor.clearColor()
}

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

部分:蓝色/灰色/没有

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

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

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

let backgroundColorView = UIView()
backgroundColorView.backgroundColor = UIColor.red
UITableViewCell.appearance().selectedBackgroundView = backgroundColorView
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];

确保你已经使用了上面的行来使用选择效果

斯威夫特4 +:

在表格单元格中添加以下行

let bgColorView = UIView()
bgColorView.backgroundColor =  .red
self.selectedBackgroundView = bgColorView

最后应该如下所示

override func setSelected(_ selected: Bool, animated: Bool)
    {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        let bgColorView = UIView()
        bgColorView.backgroundColor =  .red
        self.selectedBackgroundView = bgColorView

    }