UICollectionView - Select 视图将出现的第一个单元格

UICollectionView - Select first cell as View Will Appear

在我的集合视图中,我需要在视图出现后立即 select 第一个单元格。

我已经实现了 didSelectItemAtIndexPathdidDeselectItemAtIndexPath 当单元格被 selected 时,它显示绿色边框,而当未被 selected 时,单元格有白色边框。

我需要的是从第一个带有绿色边框的单元格开始我的应用程序。

我尝试使用 selectItemAtIndexPath 但是,第一个单元格没有显示绿色边框。我错过了什么?

override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        let firstIndexPath = NSIndexPath(forItem: 0, inSection: 0)

        frameCollectionView.selectItemAtIndexPath(firstIndexPath, animated: false, scrollPosition: .None)

    }

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        let frameCell = collectionView.cellForItemAtIndexPath(indexPath) as! FrameViewCell

        frameCell.layer.borderWidth = 2
        frameCell.layer.borderColor = UIColor.greenColor().CGColor
    }

    func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {

        let frameCell = collectionView.cellForItemAtIndexPath(indexPath) as! FrameViewCell

        frameCell.layer.borderWidth = 1
        frameCell.layer.borderColor = UIColor.whiteColor().CGColor
    }

当您以编程方式 selecting/deselecting 时,不会调用委托方法。仅当用户 selects/deselects.

时才会调用它们

更好的方法是在 class 单元格内更改 UI,例如

找到解决方案。在 viewDidLoad():

utilityClass.delay(0.1) {
            let indexPathForFirstRow = NSIndexPath(forItem: 0, inSection: 0)
            self.frameCollectionView.selectItemAtIndexPath(indexPathForFirstRow, animated: false, scrollPosition: .None)
            self.collectionView(self.frameCollectionView, didSelectItemAtIndexPath: indexPathForFirstRow)
        }