【问题标题】:auto selected Item at first load首次加载时自动选择的项目
【发布时间】:2017-10-13 18:22:23
【问题描述】:

我正在使用水平 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)

但不工作。我搜索了很多问题,但大多数问题都有相同的解决方案,并且在我的情况下不起作用。有谁能帮帮我吗?

【问题讨论】:

    标签: ios swift3 uicollectionview selecteditem didselectrowatindexpath


    【解决方案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)
    }
    

    【讨论】:

    • 我正在加载按钮操作事件的集合视图。所以我在collectionview加载后添加了这段代码。它会触发 didSelectItem 方法,但在“if let cell = collectionView.cellForItem(at: indexPath)”处失败 有什么建议吗??
    • CollectionView.layoutIfNeeded() 创造了奇迹!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多