如何以编程方式突出显示表格视图单元格?
我正在使用:
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
tableView.delegate?.tableView!(self.ordersTableView, didSelectRowAt: indexPath)我遇到的问题是单元格被选中(正在执行didSelectRowAt中指定的所有操作),但单元格现在高亮显示。它不会显示为选中状态。
我想实现的功能类似于iPad上的设置应用程序。启动应用程序后,您会看到"general“单元格已被选中并突出显示。
当用户触摸时,单元格将正确突出显示。
我甚至尝试在我的UITableViewCell子类中覆盖isSelected变量。
好吧,事实证明这是后台任务的问题。在我选择单元格之后,单元格被再次加载,这就是为什么选择不可见的原因。
发布于 2018-03-27 17:31:42
注意::你的问题标题说,你有一个单元格突出显示的查询,而你的问题描述说,你有一个单元格选择问题。两者是不同的事件。
这是一个答案,如何在表格视图行(单元格)选择上管理(设置颜色):
// make sure your tableview row selection is enabled
yourTableViewInstance.allowsSelection = true
// handle highlighted background in data source method also
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "textview") as! YourTableViewCell
cell.contentView.backgroundColor = cell.isSelected ? UIColor.red : UIColor.gray
return cell
}
// didSelectRowAtIndexPath - change background color
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? YourTableViewCell {
cell.contentView.backgroundColor = UIColor.red
}
}
// didDeselectRowAtIndexPath - change background color
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? YourTableViewCell {
cell.contentView.backgroundColor = UIColor.gray
}
}发布于 2018-03-27 13:58:27
试试这个:-
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
var selectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
selectedCell.contentView.backgroundColor = UIColor.redColor()
}发布于 2018-03-27 18:02:23
下面是处理单元格背景选择的另一个选项
class YourTableViewCell: UITableViewCell {
// override cell selection
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if self.selectedBackgroundView == nil {
let bgView = UIView()
self.selectedBackgroundView = bgView
}
self.selectedBackgroundView?.backgroundColor = selected ? UIColor.red : UIColor.gray
}
}
// enable row/cell selection
yourTableViewInstance.allowsSelection = true
// handle highlighted background in data source method also
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "textview") as! YourTableViewCell
if self.selectedBackgroundView == nil {
let bgView = UIView()
self.selectedBackgroundView = bgView
}
self.selectedBackgroundView?.backgroundColor = selected ? UIColor.red : UIColor.gray
return cell
}https://stackoverflow.com/questions/49499948
复制相似问题