我有一个包含不同单元格的集合视图,我希望能够选择多个单元格。我可以这样做,但是当我单击已经被选中的单元格时,该单元格将再次添加到数组中,从而导致重复。我想要发生的是,当它被单击时,它会将标签附加到数组中,当再次单击它时,它将从数组中删除它。下面是我到目前为止的情况。
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
}
发布于 2015-12-16 22:29:06
维护一个Set
而不是Array
。
宣布为
var setOfSelectedFriends = Set<String>()
再加上
setOfSelectedFriends.insert(arrayOfFriendsNames[indexPath.item])
用于移除,使用
setOfSelectedFriends.remove(<elementToRemove>)
您可以阅读更多关于Swift 这里的内容。
https://stackoverflow.com/questions/34327902
复制相似问题