【发布时间】:2017-07-03 05:05:09
【问题描述】:
我正在向 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时,它显示@987654328 @ 和“我很好”。
为什么会这样?
更新 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)
}
}
【问题讨论】:
标签: ios iphone swift uicollectionview uicollectionviewcell