ios - 第一次加载时自动选择项目

标签 ios swift3 uicollectionview selecteditem didselectrowatindexpath

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

我想要的是当我加载 Collection View 时,第一个项目应该加载 bottomLayer(带下划线)

我试过代码

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


collectionView(CollectionView, didSelectItemAt: indexPathForFirstRow)

但不工作。我搜索了很多问题,但大多数问题都有相同的解决方案,但在我的案例中不起作用。有人可以帮我吗?

最佳答案

如果您在按钮操作上加载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)
}

关于ios - 第一次加载时自动选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46735928/

相关文章:

ios - 在同一个 View Controller 上按下 AlertViewController 上的确定按钮后重新加载 Collection View ?

ios - 为自定义 CollectionView 添加边框

ios - 在 CABasicAnimation 中控制速度

ios - 使用自定义按钮类调用特定 View Controller

ios - Swift 3 定时事件

ios - 通过 UIActivityViewController 共享包含数据的文件

ios - 如何检索存储在 NSUserDefaults 中的所有值?

ios - 上下文菜单破坏性操作,SwiftUI

android - 谷歌地图 flutter : I am getting black screen before loading maps

ios - CollectionView 在 StackView 中消失(Swift)