I have a collection view that displays a grid of images. It allows a user to select up to three images to email to themselves. When a user taps on a cell(image) it highlights yellow and the filename is added to an array, if they tap it again it deselects, the highlight is removed and the image is removed from the array.
Once the user sends the email I use the MFMailComposeResult delegate to remove items from the array but I can't figure out how to remove the yellow highlights from the cells. Hoping someone might be able to help. THANKS.
I'm adding the filenames of the images in the didSelectItemAt and didDeselectItemAt functions.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let fileName = filenames[indexPath.item]
selectedFileNames.append(fileName)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let fileName = filenames[indexPath.item]
if let index = selectedFileNames.index(of: fileName) {
selectedFileNames.remove(at: index)
}
}
and I'm highlighting the cells in my UICollectionViewCell class
override var isSelected: Bool {
didSet {
self.layer.borderWidth = 3.0
self.layer.borderColor = isSelected ? UIColor.yellow.cgColor : UIColor.clear.cgColor
}
}
Once the email is sent here is the code using the delegate
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
if result == MFMailComposeResult.sent {
print("emailed Photos")
self.selectedFileNames.removeAll()
self.fullSizeSharableImages.removeAll()
}
}
Any idea how to clear the highlighted cells?
You'll want, for each selected index path, to call deselectItem(at indexPath: IndexPath, animated: Bool) on the collection view.
Fortunatelly, UICollectionView has a property that lists the selected index paths. So, in mailComposeController(_: didFinishWith:), you can write:
collectionView.indexPathsForSelectedItems?
.forEach { self.collectionView.deselectItem(at: $0, animated: false) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With