简体   繁体   中英

Swift UICollectionView updating cell label on click not updating live

I have been trying to figure out how to live update a uicollectionview for a while now.

I have tried to using a number of different methods to get this done, using reloadData, reloadItems, and reloadSections. Using both DispatchQueue.main.async and not.

I cannot figure out how to get it to the point where when a user selects one of the cells, to update the contents of that cell live in front of the user. Specifically make the label text bold and not bold based on the clicks on the cell.

Here is the label that I have setup in swift:

let nameLabel: UILabel = {
    let label = UILabel()
    label.text = ""
    return label
}()

Here is the didselectitem for the collectionview

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath) as! FilterCollectionViewCell
    let selected = ViewController.brands[indexPath.item]
    if FilterLauncher.selectedOptions.contains(selected){
        let loc = FilterLauncher.selectedOptions.firstIndex(of: selected)
        FilterLauncher.selectedOptions.remove(at: loc!)
        cell.nameLabel.font = UIFont.boldSystemFont(ofSize: 2.0)
        DispatchQueue.main.async {
            collectionView.reloadItems(at: [indexPath])
        }
    }
    else{
        FilterLauncher.selectedOptions.append(selected)
        cell.nameLabel.font = UIFont.boldSystemFont(ofSize: 15.0)
        DispatchQueue.main.async{
             self.collectionView.reloadItems(at: [indexPath])}

    }
}

It does end up changing the text of the selected cell to bold, but it does it on delay. It takes me trying to select another cell thats when the cell I tried to select first bolds. When I do select the cell the first time it flashes the changes I want, but then goes back.

Collection View select cell change text example

I don't think you need to call collectionView.reloadItems(at: [indexPath]) after selecting it. Accessing the cell's label directly should make the change without having to reload the cell.

My guess is that you have some dequeueing code in the cellForItemAt which sets the font to be normal, so when you tap on a cell its label gets set to bold, but then immediately set back to normal when you reload it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM