如何默认选择UICollectionView的特定索引路径?

时间:2017-02-26 06:54:09

标签: ios swift swift3 uicollectionview

我想默认突出显示UICollectionView的特定单元格 但是我不能这样做。代码如下。

UIView(在init方法中):

    let selectedIndexPath = IndexPath(item: 0, section: 0)
    collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: [])

UICollectionViewCell:

override var isSelected: Bool {
    didSet {
        imageView.tintColor = isSelected ? UIColor.white : UIColor.red
    }
}

默认情况下,如何选择UICollectionView的特定索引路径? 如果您需要任何其他信息来解决它,请告诉我。 谢谢。

2 个答案:

答案 0 :(得分:0)

您应该覆盖此方法

override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//you should set needed cells as selected here, or set it to deselected, because it is your responsibility now 
    var shouldSelect = false //or true
    cell.isSelected = shouldSelect
}

但在这种情况下,您应该跟踪collectionView(_ collectionView:UICollectionView,didSelectItemAt indexPath:IndexPath)方法并在选择时重新加载集合。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    collectionView.reloadData()
//or reload sections 
}

答案 1 :(得分:0)

我只需在下方添加,然后就可以了。

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    //add here
    let selectedIndexPath = IndexPath(item: 0, section: 0)
    collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: [])
}