pre select/highlight UICollectionViewCell on first load of view

后端 未结 9 1255
醉酒成梦
醉酒成梦 2021-02-07 05:48

Im trying to preselect the first object/UICollectionViewCell in the UICollectionView? I have tried:

self.dateCollectionView.allowsMultipleSelection=NO;

[self.da         


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 05:55

    For swift 3

    Use collectionView.selectItem with-in this overload collectionView(UICollectionView, IndexPath)

    This is my code, in this code I pre selected row with indexPath.row = 0

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = ScenarioCollectionView.dequeueReusableCell(withReuseIdentifier: "ReuseScenarioCollectionViewCell", for: indexPath as IndexPath) as! ScenarioCollectionViewCell
    
        if (indexPath.row == 0){
            collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
            cell.layer.borderColor=UIColor.gray.cgColor        
        }else{
            cell.layer.borderColor=UIColor.white.cgColor
        }
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.layer.borderColor = UIColor.gray.cgColor
            }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath as IndexPath)
        cell?.layer.borderColor = UIColor.white.cgColor
        collectionView.deselectItem(at: indexPath, animated: true)
    }
    

提交回复
热议问题