我正在向UICollectionView動態添加數據。每當我有新的數據時,它將清除所有現有的數據並加載一個新的數據集。下面是代碼,Swift - UICollectionView removeAll()暫時清除單元格
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)
}
}
是更新,對吧!我想清除所有現有的數據,這很好!但問題在於,它在將新數據加載到對話時再次出現。 – moustacheman
您可以發佈cellForItemAtIndexPath –
@aravindtrue的代碼,而不是更新'willDisplaycell'中的'textViewCell.textView'嘗試從cellForItemAtIndexPath更新'textViewCell.textView'並檢查 –