ios - Swift - UICollectionView removeAll() 暂时清除单元格

标签 ios iphone swift uicollectionview uicollectionviewcell

我正在向 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 和“我很好”。

enter image description here

为什么会出现这种情况?

更新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/

相关文章:

ios - 借助核心图形从代码创建具有渐变效果的图像?

iphone - 如何在 iPhone 中取消 ASIFormDataRequest

ios - 为什么我的 XML 解析器不断迭代 Swift 中的标签?

ios - ipad/iphone,安全应用程序分发

if 语句为 true 的 Swift Break 循环

objective-c - 用于 objective-c 的jGraphT?

iphone - FBFriendPickerViewController - 初始化之前选中的 friend

c# - Monotouch AVAssetReader

ios - 隐藏在滚动/滑动后,UINavigationBar 不会再次显示

Swift:将图像添加到 CAShapeLayer