ios - UICollectionView 重叠标签

标签 ios swift uicollectionview uicollectionviewcell

我正在使用 collectionview 并且第一个数据加载工作正常。当标签重叠时第二次加载数据时会出现问题,因为旧标签似乎仍然存在。 下面是我的 collectionview 代码,在此先感谢。

          func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                let customCell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCellIdentifier", for: indexPath)
                customCell.layer.borderColor = UIColor.black.cgColor
                customCell.layer.borderWidth = 1


    // changed these lines here
                if cellsLabels[indexPath.row] != nil {
                    customCell.willRemoveSubview(cellsLabels[indexPath.row]!)
                }
    //to these lines here and the problem was solved
            let maybe = customCell.subviews

            for i in 0 ..< maybe.count {
                maybe[i].removeFromSuperview()
            }
                let c

ommentLabel = UILabel()
            commentLabel.text = commentsArray[indexPath.row]
            commentLabel.frame = CGRect(x: 0, y: 50, width: 200, height: 30)
            customCell.addSubview(commentLabel)

            self.cellsLabels[indexPath.row] = commentLabel

            if indexPath.row == commentLoadTracker*10 - 1 {
                print("working doomfist")
            }

            return customCell
        }

        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

            return commentsArray.count
        }

        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            var cellSize = CGSize()
            cellSize.width = self.commentView.frame.width
            cellSize.height = 100
            return cellSize
        }

最佳答案

customCell.willRemoveSubview

您正在调用 willRemoveSubiew 而不是 removeFromSuperview

if cellsLabels[indexPath.row] != nil {
    cellsLabels[indexPath.row]!.removeFromSuperview()
}

不需要调用willRemoveSubview,UIKit会为你调用它,它的存在只是为了它可以是

Overridden by subclasses to perform additional actions before subviews are removed from the view.

关于ios - UICollectionView 重叠标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45091389/

相关文章:

ios - 应用程序在 iOS 8.4 上崩溃

objective-c - UITableView setEditing 为 NO 不会改变 barButtonItem

ios - 应如何为推送通知服务设置代码签名?

ios - 自定义 UICollectionViewCell 自动布局 NSInternalInconsistencyException 错误

ios - Swift 4 转换错误 - 类型 'NSAttributedStringKey' 没有成员 'foregroundColorNSAttributedStringKey'

ios - 尝试在闭包内使用常量属性时 Xcode 出错

ios - 如何将字符串转换为数据

ios - "Creating an image format with an unknown type is an error"通过WKWebView显示WebApp时

ios - 使用 AutoLayout 使 UICollectionViewCell 的高度与其内容(所有 subview 的总高度)相匹配

ios - 我应该使用 xcassets 还是只更改一张图像的大小以在 iOS 的多个设备上开发?