表格单元格选择颜色工作在0单元格之后但不是第一行?
问题描述:
我改变了tableview单元格的选择颜色,它只适用于第1行及其后的行,但第0行“first”并不表示默认的浅灰色。表格单元格选择颜色工作在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
}
答
你有没有意识到,你换所有细胞外观上与此调用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)
答
如果你只是想改变背景颜色,你并不需要创建一个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
}
据,因为我能理解,@marrioa需要改变选择颜色 –
好,我想在这种情况下,他使用了错误的委托方法。它应该在didSelectRowAt ...委托方法 – Lukas
我会编辑我的答案,这种情况下 – Lukas