UICollectionView - 选择第一个单元格作为View将出现

时间:2016-04-01 21:32:59

标签: ios uicollectionview uicollectionviewcell swift2.2

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

我已实施didSelectItemAtIndexPathdidDeselectItemAtIndexPath当选择单元格时,如果未选择单元格,则显示绿色边框,单元格具有白色边框。

我需要的是使用带有绿色边框的第一个单元格启动我的应用程序。

我尝试使用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
    }

2 个答案:

答案 0 :(得分:1)

以编程方式选择/取消选择时,不会调用委托方法。只有在用户选择/取消选择时才会调用它们。

更好的方法是更改​​单元格类中的UI,例如参见Trying to override "selected" in UICollectionViewCell Swift for custom selection state

答案 1 :(得分:1)

找到解决方案。在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)
        }