首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何在选择和取消选择单元时只保留数组中的不同元素?

如何在选择和取消选择单元时只保留数组中的不同元素?
EN

Stack Overflow用户
提问于 2015-12-16 22:23:04
回答 1查看 37关注 0票数 0

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

代码语言:javascript
运行
AI代码解释
复制
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
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-16 22:29:06

维护一个Set而不是Array

宣布为

代码语言:javascript
运行
AI代码解释
复制
var setOfSelectedFriends = Set<String>()

再加上

代码语言:javascript
运行
AI代码解释
复制
setOfSelectedFriends.insert(arrayOfFriendsNames[indexPath.item])

用于移除,使用

代码语言:javascript
运行
AI代码解释
复制
setOfSelectedFriends.remove(<elementToRemove>)

您可以阅读更多关于Swift 这里的内容。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34327902

复制
相关文章

相似问题

领券
社区富文本编辑器全新改版!诚邀体验~
全新交互,全新视觉,新增快捷键、悬浮工具栏、高亮块等功能并同时优化现有功能,全面提升创作效率和体验
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文