修改 uicollectionview 中的特定单元格

Modify specific cell in uicollectionview

当使用 cellForItemAtIndexPath 将单元格添加到我的 UICollectionView 时,我试图定位第一个单元格并向单元格中的图像添加彩色叠加层。然而,代码似乎在创建时针对多个单元格(尽管不是全部),即使它似乎没有被调用相应的次数(它可能将覆盖应用于 3 或 4 个单元格,但只调用它两次 [第二次是在调用 reloadData() 时])。如何将颜色叠加应用于第一个且仅应用于第一个单元格?

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ProfileCollectionViewCell

    if(self.userList.count > 0) {
        cell.frame.size = CGSize(width: 202, height: 207)
        if(indexPath.item < self.userList.count) {
            cell.myImage.image = self.userList[indexPath.item].image
            cell.myImage.layer.cornerRadius = cell.myImage.frame.size.width / 2
            cell.myImage.layer.masksToBounds = true
            if(indexPath.item == 0) {
                print("Overlay")
                let circlePath = UIBezierPath(arcCenter: CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2), radius: CGFloat((cell.myImage?.frame.size.width)! / 2), startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2), clockwise: true)
                let shapeLayer = CAShapeLayer()
                shapeLayer.path = circlePath.CGPath
                shapeLayer.fillColor = self.overlayColor.CGColor

                cell.layer.addSublayer(shapeLayer)
            }
         }
     }
     return cell
 }

如果您使用 itemrow 没有问题,您必须放入 else 并删除 CAShapeLayer 否则它将显示在其他单元格项目中,因为该单元格将被重用.用下面的代码替换你的代码。

if(indexPath.item == 0) {   // if(indexPath.row == 0) {
   let circlePath = UIBezierPath(arcCenter: CGPoint(x: cell.frame.width / 2, y: cell.frame.height / 2), radius: CGFloat((cell.myImage?.frame.size.width)! / 2), startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2), clockwise: true)
   let shapeLayer = CAShapeLayer()
   shapeLayer.path = circlePath.CGPath
   shapeLayer.fillColor = self.overlayColor.CGColor

   cell.layer.addSublayer(shapeLayer)
} else {
   let sublayers = cell.layer.sublayers
   for sublayer in sublayers! {
        if sublayer.isKindOfClass(CAShapeLayer) {
            sublayer.removeFromSuperlayer()
        }
   }
}