Swift:自定义UITableViewCell背景色
效果前言前段时间在整理课件 《 实现在UITableViewCell的子类文件( override func setSelected(selected: Bool,animated: Bool) {
super.setSelected(selected,animated: animated)
// Configure the view for the selected state
if selected {
self.backgroundColor = UIColor.orangeColor()
}else {
self.backgroundColor = UIColor.whiteColor()
}
}
运行工程,可能你会发现,当你点击单元格的时候,选中样式依旧是系统样式,如下图: 这是什么原因导致的呢?打开视图层级,我们就会发现,其实我们已经设置成功了,只是被遮住了,如下图: 那应该如何解决呢?其实很简单,只需要修改cell的 cell.selectionStyle = UITableViewCellSelectionStyle.None
现在,我们就完成了自定义单元格选中样式了,特简单吧? 延伸有时可能会有这种需求,就是我不需要选中背景色,但是我想在点击某个单元格的时候闪一下,即背景色突变一下就OK,像这种需求又改如何解决呢? 首先,我们需要实现如下方法,当单元格不管是选中也好,未选中也罢,都设为白色。 override func setSelected(selected: Bool,animated: animated)
// Configure the view for the selected state
if selected {
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) {
if highlighted {
self.backgroundColor = UIColor.redColor()
}else {
self.backgroundColor = UIColor.whiteColor()
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |