我更改了tableview单元格选择颜色,它仅适用于第1行及更高版本,但第0行“第一”并未显示默认的浅灰色。
我做错了吗?
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
// Configure the cell...
let colorView = UIView()
let green = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0)
colorView.backgroundColor = green
UITableViewCell.appearance().selectedBackgroundView = colorView
cell.textLabel?.text = "#" + books[indexPath.row]
return cell
}
答案 0 :(得分:1)
如果您只想更改背景颜色,则无需创建UIView并为其设置背景颜色。而是改变contentView背景,它应该在didSelectRow ...方法中。不在cellForRow ..因为表视图加载每个单元格
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let green = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0)
tableView.cellForRowAtIndexPath(indexPath)?.contentView.backgroundColor = green
}
答案 1 :(得分:1)
您是否意识到,使用此调用UITableViewCell.appearance().selectedBackgroundView = colorView
更改了所有单元格外观?因此,每次您的表格视图要求一个单元格时,您创建新视图,将其称为colorView
并替换所有先前创建的单元格的selectedBackgroundView
?你在做什么。
移动此
let colorView = UIView()
let green = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0)
colorView.backgroundColor = green
UITableViewCell.appearance().selectedBackgroundView = colorView
到您的viewDidLoad
方法。
但是,只有当您不仅需要选定单元格的绿色,而且还需要更复杂的东西时,它就可以了。
最好在cellForRowAtIndexPath
cell.selectedColor = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0)