我正在向 UICollectionView 动态添加数据。每当我有新数据时,它都会清除所有现有数据并加载新数据集。这是代码,
self.conversation.removeAll()
self.collectionView.reloadData()
self.conversation.insert(messageWrapper(description: "Some text", origin: "user"), at: 0)
self.collectionView.reloadData()
ItemAtIndexPath
中的代码
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let textViewCell = cell as! TextCollectionViewCell
let description = conversation[indexPath.row].description
let origin = conversation[indexPath.row].origin
textViewCell.textView.text = description
textViewCell.textView.textAlignment = origin == "arvis" ? NSTextAlignment.left : NSTextAlignment.right
}
问题它删除了所有现有数据,并且在加载新数据时,它与以前的数据重叠,即,假设我有 Hello
并在添加 时我很好
,它在上面显示 Hello
和“我很好”。
为什么会出现这种情况?
更新1:
cellForItemAt
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let textViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "textViewCell", for: indexPath) as! TextCollectionViewCell
let description = conversation[indexPath.row].description
let origin = conversation[indexPath.row].origin
textViewCell.awakeFromNib()
textViewCell.textView.text = description
textViewCell.textView.textAlignment = origin == "arvis" ? NSTextAlignment.left : NSTextAlignment.right
return textViewCell
}
TextCollectionViewCell
单元格的标识符类
class TextCollectionViewCell: UICollectionViewCell {
var textView: UITextView!
override func awakeFromNib() {
textView = UITextView(frame: contentView.frame)
textView.textColor = UIColor.white
textView.font = UIFont.systemFont(ofSize: 18)
textView.layer.backgroundColor = UIColor.clear.cgColor
textView.contentMode = .scaleAspectFill
textView.clipsToBounds = true
contentView.addSubview(textView)
}
}
最佳答案
现有数据被清除,因为您正在清除collectionView的数据源并重新加载它。
只需尝试将新值附加到 conversation
数组,然后重新加载 collectionView。
如果问题在于重叠,只需尝试从 cellForItemAtIndexPath
更新 textViewCell.textView
,而不是更新 willDisplaycell< 中的
textViewCell.textView
/
关于ios - Swift - UICollectionView removeAll() 暂时清除单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44878130/