gpt4 book ai didi

arrays - 取消选择 Collection View 中的项目并将其从无效的数组中删除

转载 作者:行者123 更新时间:2023-11-28 12:13:23 25 4
gpt4 key购买 nike

我试图选择一个单元格并将该单元格的内容添加到数组中,然后能够取消选择一个单元格并从数组中删除相同的对象。我已经苦苦挣扎了几天,但似乎仍然无法正常工作。选择和取消选择功能有效,它将对象添加到数组,但在取消选择时,我不知道如何从数组中删除相同的对象。如何取消选择单元格并将其从数组中删除?

这是我的代码:

    struct Friends {
var friendName : String!
}

struct SelectedMembers {
var selectedFriend : String!
}


var friends = [Friends]()
var selectedFriends = [SelectedMembers]()

//MARK: Select multiple cells
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? FriendsCell
selectedCell.append(indexPath)
cell?.contentView.backgroundColor = .red
print("Friends are: \(String(describing: cell?.nameSurname.text!))")

if (cell?.isSelected)! {
print("this is selected...")
var selection = SelectedMembers()
selection.selectedFriend = friends[indexPath.item].friendName
selectedFriends.append(selection)

print(selectedFriends)

}




}

//MARK: Deselect Multiple cells
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let deselectedCell = collectionView.cellForItem(at: indexPath) as? FriendsCell
print(indexPath.row)
if let index = selectedFriends.index(of: selectedFriends[indexPath.row]) {
selectedFriends.remove(at: index)
}

if selectedCell.contains(indexPath) {
selectedCell.remove(at: selectedCell.index(of: indexPath)!)
deselectedCell?.contentView.backgroundColor = .white
print(selectedCell)
}


print(selectedFriends)
}
}

最佳答案

这段代码是罪魁祸首。

if let index = selectedFriends.index(of: selectedFriends[indexPath.row]) {selectedFriends.remove(at: index)}

例如,如果您有 100 行,并且您选择了 1、10、50 个单元格,则您的 selectedFriends 数组仅包含 3 个对象,但是当有人取消选择第 50 个单元格时,在上面的代码您正在尝试访问 selectedFriends[50]..所以这是不正确的。

you don't need to maintain selectedCell array to keep track of selected/unselected indexes. Whenever a cell is selected you will get a callback in didSelecte and only selected cells only can be deselected.

将下面的代码放在didDeselect()中

let deselectedCell = collectionView.cellForItem(at: indexPath) as? FriendsCell
deselectedCell?.contentView.backgroundColor = .white
let friendName = friends[indexPath.item].friendName
var deselectedIndex:Int
for (index,value) in selectedFriends.enumerated() { if value.friendName == freindName { deselectedIndex = index }}
selectedFriends.remove(at:deselectedIndex}

It is better to use Dictionary if your friend list is more, so you can avoid the for loop to find the deselected friend. Implement Equatable protocol instead of checking the only name if you go ahead with array implementation.

关于arrays - 取消选择 Collection View 中的项目并将其从无效的数组中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47685839/

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