我有一个 tableViewController
,它具有三个函数,其中两个运行成功。
按工具栏内的按钮添加单元格 = 有效
能够将文本插入到单元格内的 UITextView 中,而无需复制和移动文本 = 有效
按下单元格中的按钮时,会出现 checkMarkImage,在滚动和四处移动时不会重复 = 不起作用
checkMarkImage
不会停留在按下按钮的单元格中。它会在滚动时重新出现,有时会消失,尽管我努力使用 bool 值来跟踪已勾选的单元格。
我的 customCellClass 中按钮的配置:
@IBAction func checkMarkButton(_ sender: UIButton) {
if checkedOff{
UIImageView.animate(withDuration: 0.3, delay: 0, options: [], animations: {
self.checkMarkImage.alpha = 0.0
self.notesTextView.isEditable = true
self.notesTextView.textColor = .white
self.checkedOff = false
},completion: nil)
}
else{
UIImageView.animate(withDuration: 0.3, delay: 0, options: [], animations: {
self.checkMarkImage.alpha = 1.0
self.notesTextView.isEditable = false
self.notesTextView.textColor = .orange
self.checkedOff = true
}, completion: nil)
}
}
cellForRowAt
中单元格的处理:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "TableViewNotesCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! TableViewNotesCell
cell.notesTextView.text = cellNumber[indexPath.row]
if cellNumber[indexPath.row] < " "{
print("celltext is less than nothing")
cell.notesTextView.textColor = .white
cell.notesTextView.isEditable = true
cell.checkMarkImage.alpha = 0.0
}
else{
if cell.checkedOff{
print("cell has been checked off")
cell.notesTextView.textColor = .orange
cell.notesTextView.isEditable = false
cell.checkMarkImage.alpha = 1.0
}
}
我希望单元格的 checkMarkImage
停留在按下按钮的单元格,但实际效果是 checkMarkImage
重新出现,当滚动时,有时会完全消失
最佳答案
我担心这样做不会达到预期的结果。
当您使用 UITableView
或 UICollectionView
时,您必须保留您的数据,因为它们在滚动时会重用 Cell
。因此,当您滚动 UITableView 时,您会得到重复的图像或有时会丢失它。你可以做的是:
- 使用字典数组作为
dataSource
来保存 TableView 的数据。 - 您也可以创建自己的模型并用作
TableView
的数据源。 - 如果您的数据足够大,那么您可以选择
CoreData
/Sqllight
。
关于swift - 如何保存在单元格内按下按钮的操作,以便我可以添加图像而不会复制或消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54034147/