单元格backgroundColor插入一行时清除奇怪的行为

不是重复的:
问题/答案是关于改变颜色。 我改变单元格的颜色没有问题,而是在“颜色”, .clear并插入单元格时出现问题,单元格正在“重置”。

每当我将我的单元格的背景颜色设置为.clear并在表格中插入一行时,单元格将自动“重置”到其原始状态。 当背景颜色具有值时不会发生这种情况。

例如:

 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let gesture = UIPanGestureRecognizer() gesture.addTarget(self, action: #selector(handlePan)) gesture.delegate = self addGestureRecognizer(gesture) backgroundColor = .clear } func handlePan(_ recognizer: UIPanGestureRecognizer) { if recognizer.state == .changed { let translation = recognizer.translation(in: self).x contentView.frame.origin.x += translation recognizer.setTranslation(.zero, in: self) } if recognizer.state == .ended { guard let index = delegate?.tableView.indexPath(for: self) else { return } delegate?.insert(index) } } 

我的ViewController:

 func insert(_ index: IndexPath) { let cell = tableView.cellForRow(at: index) as? PannableCell items.append("some") let path = IndexPath(row: index.row + 1, section: index.section) tableView.insertRows(at: [path], with: .fade) } 

题:
我如何设置我的单元格的背景颜色。 .clear并插入一行,没有单元格被重置? 我想这是因为插入单元格后,我想将原始单元格恢复到原始位置。

编辑
设置backgroundColor的颜色只适用于iOS 9.在iOS 10中,它仍然以某种方式重置单元格。

将您的插入更改为:

 tableView.beginUpdates() tableView.insertRows(at: [path], with: .fade) tableView.endUpdates() 

尝试在你的tableView上使用beginUpdates()endUpdates()

 tableView.beginUpdates() // insert, delete your rows here tableView.endUpdates() 

如果你不使用这些方法,你可能会遇到各种各样的错误,包括无效的行数,UI毛刺等。

如果它没有帮助,你可以尝试通过在你的单元格的prepareForReuse方法中设置所需的颜色或在tableView:willDisplayCell:forRowAtIndexPath: delegate方法中设置所需的颜色(尝试避免像这样脏的修复)。