0

我正在使用水平collectinview來顯示項目。當用戶選擇/取消選擇我在文本下添加/刪除白色邊框的項目時。自動選中項目在第一次加載

這裏是代碼

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 

    if let cell = collectionView.cellForItem(at: indexPath) { 

     if cell.isSelected { 

      bottomLayer.frame = CGRect(x: 0, y: (cell.frame.height) - 7, width: (cell.frame.width), height: 3) 
      bottomLayer.backgroundColor = UIColor.white.cgColor 
      cell.layer.addSublayer(bottomLayer) 
     } 
    } 
} 


func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { 

    if collectionView.cellForItem(at: indexPath) != nil { 

      bottomLayer.backgroundColor = UIColor.green 
    } 
} 

我想,當我加載集合視圖第一個項目應與bottomLayer加載(帶下劃線)

我試過的代碼是

let indexPathForFirstRow = IndexPath(row: 0, section: 0) 
CollectionView.selectItem(at: indexPathForFirstRow, animated: true, scrollPosition: []) 


collectionView(CollectionView, didSelectItemAt: indexPathForFirstRow) 

但不工作。我搜索了很多問題,但大多數都有相同的解決方案,而且它不適用於我的案例。有誰能幫我在這裏嗎?

回答

1

如果您在按鈕動作加載CollectionView,然後

CollectionView.layoutIfNeeded() 
let indexPathForFirstRow = IndexPath(row: 0, section: 0) 
CollectionView.selectItem(at: indexPathForFirstRow, animated: true, scrollPosition: []) 
collectionView(CollectionView, didSelectItemAt: indexPathForFirstRow) 

叫它viewDidAppear

override func viewDidAppear(_ animated: Bool) { 
    let indexPathForFirstRow = IndexPath(row: 0, section: 0) 
    CollectionView.selectItem(at: indexPathForFirstRow, animated: true, scrollPosition: []) 
    collectionView(CollectionView, didSelectItemAt: indexPathForFirstRow) 
} 
+0

我加載按鈕操作事件的CollectionView。所以我在加載collectionview之後立即添加了這段代碼。它觸發didSelectItem方法,但它失敗'如果讓細胞= collectionView.cellForItem(at:indexPath)'任何建議? – iUser

+0

'CollectionView.layoutIfNeeded()'做了魔法!非常感謝你。 – iUser

相關問題