Changing cell background color in UICollectionView in Swift

前端 未结 3 1013
执笔经年
执笔经年 2020-12-09 11:48

I am using horizontal collection view to scroll dates. Collection view contain 30 cells. If I select first cell, to indicate the selection, cell background color has been ch

3条回答
  •  抹茶落季
    2020-12-09 12:16

    var selectedIndex = Int ()
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    
        if selectedIndex == indexPath.row
        {
            cell.backgroundColor = UIColor.green
        }
        else
        {
            cell.backgroundColor = UIColor.red
        }
    
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        selectedIndex = indexPath.row
    
        self.yourCollctionView.reloadData()
    }
    

    May be crazy, But it works fine for me...!

提交回复
热议问题