Reputation: 35
When adding cells to my UICollectionView using the cellForItemAtIndexPath I'm trying to target the first cell and add a coloured overlay to the image in the cell. However, the code seems to target multiple cells as they are created (though not all) even though it doesn't seem to be called a corresponding number of times (It may apply the overlay to 3 or 4 cells but only call it twice [the second time is when reloadData() is called]). How do I apply the colour overlay to the first and only to the first cell?
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
}
Upvotes: 0
Views: 860
Reputation: 1564
there is no problem if you use item
or row
you have to put else and remove CAShapeLayer
otherwise it will show in the other cell item because the cell will be reuse. replace your code with below.
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()
}
}
}
Upvotes: 1