在uicollectionview中修改特定单元格

时间:2016-08-11 06:26:51

标签: swift uicollectionview uicollectionviewcell

使用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
 }

1 个答案:

答案 0 :(得分:1)

如果您使用itemrow,则必须放置其他内容并移除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()
        }
   }
}