gpt4 book ai didi

ios - 如何在选择和取消选择单元格时仅保留数组中的不同元素?

转载 作者:行者123 更新时间:2023-11-29 01:23:25 26 4
gpt4 key购买 nike

我有一个包含不同单元格的 Collection View ,我希望能够选择多个单元格。我能够这样做,但是当我单击一个已经被选中的单元格时,同一个单元格会再次添加到数组中,从而导致重复。我想要发生的是当它被点击时它会将标签附加到数组,当它再次被点击时它会从数组中删除它。以下是我目前所拥有的。

func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
arrayOfFriendsSelected.append(arrayOfFriendsNames[indexPath.item])
print(arrayOfFriendsSelected)
var cell = collection.cellForItemAtIndexPath(indexPath) as! ShareCell
cell.friendimage.layer.borderWidth = 3.0
cell.friendimage.layer.borderColor = UIColorFromRGB("4F26D8").CGColor

return true
}

func collectionView(collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
var cell = collection.cellForItemAtIndexPath(indexPath) as! ShareCell
arrayOfFriendsSelected.removeAtIndex(indexPath.item)
print(arrayOfFriendsSelected)
cell.friendimage.layer.borderWidth = 0.0

return true
}

最佳答案

维护一个 Set 而不是 Array

声明喜欢

var setOfSelectedFriends = Set<String>()

并添加

setOfSelectedFriends.insert(arrayOfFriendsNames[indexPath.item])

要删除,请使用

setOfSelectedFriends.remove(<elementToRemove>)

您可以阅读有关 Swift Sets 的更多信息 here .

关于ios - 如何在选择和取消选择单元格时仅保留数组中的不同元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34327902/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com