save selected row in UITableView after reloadData

后端 未结 14 1022
后悔当初
后悔当初 2020-12-24 11:20

I write custom jabber client in iphone.

I use xmppframework as engine.

And I have UITableViewController with NSMutableArray for repesent contact list.

<
14条回答
  •  青春惊慌失措
    2020-12-24 12:02

    I solved it better by declaring an array to store, let's say, the ID or String Text of the cell you have selected, and adding it on the didSelectItemAtIndexPath function. This way, even if the number of rows changes, the selected ones won't. For example:

    var selectedItems: [String] = [] // This array type really depends on your preference and what property you're using to store
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let cell = collectionView.cellForItem(at: indexPath) else { return }
        selectedItems.append(cell.textField.text)
    }
    

    And on your initial cellForItemAtIndexPath

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath)
        if let text = cell.textField.text {
            if selectedItems.contains(text) {
                collectionView.selectItem(at: indexPath, animated: true, scrollPosition: [])
            }
        }
        return cell
    }
    

提交回复
热议问题