Change Background of UICollectionView Cell on Tap

后端 未结 6 900
时光说笑
时光说笑 2020-12-08 04:13

I have a UICollectionView that I have created programmatically. I would like for the collection view to behave in the following way:

1. User touches cell
2.          


        
6条回答
  •  無奈伤痛
    2020-12-08 05:09

    Add all the subviews inside contentView, use backgroundView and selectedBackgroundView from UICollectionViewCell. Do not set contentView.backgroundColor.

    // Add this inside your cell configuration.
    private func setupSelectionColor() {
        let backgroundView = UIView()
        backgroundView.backgroundColor = .white
        self.backgroundView = backgroundView
    
        let selectedBackgroundView = UIView()
        selectedBackgroundView.backgroundColor = .orange
        self.selectedBackgroundView = selectedBackgroundView
    }
    
    // Add the deselection inside didSelectCallback
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
    }
    

提交回复
热议问题