I have a UICollectionView where the cells are given a blue border when tapped. The problem is that when I scroll down to more cells, some of the new cells imitate the blue border without ever having been tapped. Anybody know how to fix this?
Code:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tradeImages.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: OffersCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell4", forIndexPath: indexPath) as! OffersCollectionViewCell
tradeImages[indexPath.row].getDataInBackgroundWithBlock{
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.offersImg.image = image
}
}
return cell
}
func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
var cell = self.collectionView.cellForItemAtIndexPath(indexPath)
if cell!.tag == 0 {
cell!.layer.borderWidth = 2.0
cell!.layer.borderColor = UIColor.blueColor().CGColor
offersArray.append(objectsArray[indexPath.row] as! PFObject)
cell!.tag = 1
} else {
cell!.layer.borderWidth = 0.0
cell!.tag = 0
if let index = find(offersArray, objectsArray[indexPath.row] as! PFObject) {
offersArray.removeAtIndex(index)
}
}
return true
}
Use the method prepareForReuse()
in your OffersCollectionViewCell
and set the initial values there for your cells for reuse.
For example:
override func prepareForReuse() {
super.prepareForReuse()
layer.borderWidth = 0.0
layer.borderColor = UIColor.whiteColor().CGColor
// Other initial values
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.