Swift:滚动时UICollectionView标签和图像的单元格复制

时间:2017-05-22 22:53:43

标签: ios swift uicollectionview

出于某种原因,当我滚动UICollectionView Cell上的标签时,会在当前标签上添加标签,如下所示:

enter image description here

这是我的代码:

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath)
    let centerY = (myCell.frame.size.height / 2) - 50
    let title = PaddingLabel(frame: CGRect(x: 120, y: centerY, width: 200, height: 100))

    let size = CGRect(x: 10, y: centerY, width: 100, height: 100)

    let imageview: UIImageView = UIImageView(frame: size)
    let image: UIImage = UIImage(named: categoryImages[indexPath.row])!
    imageview.image = image


    title.textAlignment = .left
    title.clipsToBounds = true
    title.numberOfLines = 2
    title.font = title.font.withSize(25)
    title.text = categoryTopics[indexPath.row]

    switch (categoryColours[indexPath.row] ) {
    case ("ef5c42"):
        myCell.backgroundColor = UIColor(r: 239,g: 92,b: 66)
        title.textColor = .white
    case ("red"):
        myCell.backgroundColor = UIColor.red
    case ("green"):
        myCell.backgroundColor = UIColor.green
    case ("blue"):
        myCell.backgroundColor = UIColor.blue
    default:
        myCell.backgroundColor = UIColor.yellow
        title.textColor = .white
    }


    myCell.contentView.addSubview(title)
    myCell.contentView.addSubview(imageview)

    return myCell
}

我尝试过添加:

for view in cell.subviews {
   view.removeFromSuperview()
}

但这似乎只显示一个空单元格。

2 个答案:

答案 0 :(得分:2)

如果你每次都要从头开始构建细胞,你可能只是懒惰而不是将它出列。

即改变:

let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath)

为:

let myCell = UICollectionViewCell()

虽然我很惊讶但是在将它出列后立即删除所有子视图并不起作用。以下看起来很好。

let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath)
for view in myCell.contentView.subviews {
   view.removeFromSuperview()
}

虽然我同意Barns52,但最好的要做的事情是创建一个自定义的UITableViewCell,它将您的样式与标签和图像等相匹配,然后设置图像和标签每次都不重新创建它们,并且每次都将它们添加为子视图。

答案 1 :(得分:1)

您正在尝试在tableview中创建自定义单元格,但在迭代单元格时添加视图。您需要为您的单元格创建一个自定义类,并将要使用的视图添加到其中。

然后你需要像这样出局:

let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath) as! yourCustomClass

然后只需将您的数据添加到yourCustomClass中的视图中,如下所示:

myCell.title.text = categoryTopics[indexPath.row]

let image: UIImage = UIImage(named: categoryImages[indexPath.row])!
myCell.imageview.image = image