2

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

用户发送电子邮件后,我使用 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 类中的单元格

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

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

4

2 回答 2

10

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

幸运的是,UICollectionView有一个列出所选索引路径的属性。因此,在 中mailComposeController(_: didFinishWith:),您可以编写:

collectionView.indexPathsForSelectedItems?
    .forEach { self.collectionView.deselectItem(at: $0, animated: false) }
于 2017-02-27T02:26:37.657 回答
0

不如 tomahh 优雅的解决方案,但你可以打电话

collectionView.allowsSelection = false
collectionView.allowsSelection = true

它会清除选择

于 2020-09-04T09:03:29.590 回答