UICollectionView重叠标签

时间:2017-07-13 21:42:38

标签: ios swift uicollectionview uicollectionviewcell

我正在使用集合视图,第一个数据加载工作正常。当标签重叠第二次加载数据时会出现问题,因为旧标签似乎仍然存在。 以下是我的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
        }

1 个答案:

答案 0 :(得分:1)

  

customCell.willRemoveSubview

您正在呼叫willRemoveSubiew而不是removeFromSuperview

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

无需拨打willRemoveSubview,UIKit会为您调用它,它只存在以便它可以

  

在从视图中删除子视图之前,子类重写以执行其他操作。