0

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

I have implemented didSelectItemAtIndexPathand didDeselectItemAtIndexPathWhen the cell is selected it shows a green border when is not selected the cell has a white border.

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

但是,我尝试使用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
    }
4

2 回答 2

1

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

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

于 2016-04-01T22:22:01.613 回答
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)
        }
于 2016-04-01T23:50:12.480 回答