Swift设置UITableViewCell 背景色

在UITableViewCell的子类文件(CustomTableViewCell.swift)中实现如下方法即可

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

    super.setSelected(selected, animated: animated)


    // Configure the view for the selected state

    ifselected {

        self.backgroundColor = UIColor.orangeColor()

    }else{

        self.backgroundColor = UIColor.whiteColor()

    }

}

运行工程,可能你会发现,当你点击单元格的时候,选中样式依旧是系统样式,如下图:

这是什么原因导致的呢?打开视图层级,我们就会发现,其实我们已经设置成功了,只是被遮住了,如下图:

那应该如何解决呢?其实很简单,只需要修改cell的selectionStyle属性即可,如下所示:

1cell.selectionStyle = UITableViewCellSelectionStyle.None

现在,我们就完成了自定义单元格选中样式了,特简单吧?

延伸

有时可能会有这种需求,就是我不需要选中背景色,但是我想在点击某个单元格的时候闪一下,即背景色突变一下就OK,像这种需求又改如何解决呢?

首先,我们需要实现如下方法,当单元格不管是选中也好,未选中也罢,都设为白色。


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

    super.setSelected(selected, animated: animated)


    // Configure the view for the selected state


    ifselected {

        self.backgroundColor = UIColor.whiteColor()

    }else{

        self.backgroundColor = UIColor.whiteColor()

    }

}

其次,在代理方法中,做如下操作:


func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {


    let cell = tableView.cellForRowAtIndexPath(indexPath)


    // change the cell background color

    cell?.backgroundColor = UIColor.redColor()

}

除了在代理方法中操作,还可以在自定义单元格中实现,效果一致,只是无需通过代理方法实现,具体实现如下:


override func setHighlighted(highlighted: Bool, animated: Bool) {

    ifhighlighted {

        self.backgroundColor = UIColor.redColor()

    }else{

        self.backgroundColor = UIColor.whiteColor()

    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容