如何清除 UI 集合视图中选定的突出显示单元格

How to clear selected highlighted cells in UI Collection View

我有一个显示图像网格的集合视图。它允许用户将最多 select 三张图片通过电子邮件发送给自己。当用户点击一个单元格(图像)时,它会突出显示黄色并将文件名添加到数组中,如果他们再次点击它,它会消失selects,突出显示将被删除,图像也会从数组中删除。

用户发送电子邮件后,我使用 MFMailComposeResult 委托从数组中删除项目,但我不知道如何从单元格中删除黄色突出显示。希望有人能提供帮助。谢谢。

我在 didSelectItemAt 和 didDeselectItemAt 函数中添加图像的文件名。

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)
    }    
}

并且我在我的 UICollectionViewCell 中突出显示单元格 class

override var isSelected: Bool {
    didSet {
        self.layer.borderWidth = 3.0
        self.layer.borderColor = isSelected ? UIColor.yellow.cgColor : UIColor.clear.cgColor
    }
} 

发送电子邮件后,这里是使用委托的代码

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()     
    }
}

知道如何清除突出显示的单元格吗?

对于每个选定的索引路径,您需要在集合视图上调用 deselectItem(at indexPath: IndexPath, animated: Bool)

幸运的是,UICollectionView 有一个 属性 列出了选定的索引路径。所以,在mailComposeController(_: didFinishWith:)中,你可以这样写:

collectionView.indexPathsForSelectedItems?
    .forEach { self.collectionView.deselectItem(at: [=10=], animated: false) }

不如 tomahh 优雅的解决方案,但你可以调用

collectionView.allowsSelection = false
collectionView.allowsSelection = true

它会清除选择