我正在向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
并添加I am good
,它会显示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)
}
}
答案 0 :(得分:0)
现有数据被清除,因为您正在清除collectionView的数据源并重新加载它。
尝试将新值附加到conversation
数组,然后重新加载collectionView。
如果问题与过度使用相关,请尝试从textViewCell.textView
更新cellForItemAtIndexPath
,而不是更新textViewCell.textView
中的willDisplaycell
答案 1 :(得分:0)
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
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
return textViewCell
}
尝试此操作,而不是在willDisplay cell:
使用cellForItemAt indexPath: