【问题标题】:How to keep only distinct elements in Array while selecting and deselecting cells?如何在选择和取消选择单元格时仅保留 Array 中的不同元素?
【发布时间】:2015-12-17 06:23:04
【问题描述】:

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

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
}

【问题讨论】:

  • 仅使用 didSelect 项目委托方法。在添加到数组之前,通过使用数组包含方法检查对象是否 der。如果 der 删除,则添加。
  • 与其使用数组,不如使用集合。然后就可以快速查看好友是否已经在集合中了

标签: ios swift set


【解决方案1】:

维护Set 而不是Array。

声明喜欢

var setOfSelectedFriends = Set<String>()

并添加

setOfSelectedFriends.insert(arrayOfFriendsNames[indexPath.item])

要删除,请使用

setOfSelectedFriends.remove(<elementToRemove>)

你可以阅读更多关于 Swift Sets here.

【讨论】:

  • 我如何删除一个对象,就像在 shouldDeselect 函数中一样?
  • 由于某种原因,未调用 shouldDeselect 函数。有什么理由吗?
  • 你应该使用 didSelect 函数而不是 shouldSelect。此外,这可能是一个完全不同的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多