在collectionviews之间传递indexPath

时间:2016-12-30 14:06:25

标签: ios swift uicollectionview swift3

我正在尝试传递用户点击的单元格的indexPath,以便当segue执行collectionView滚动到正确的单元格时。但我被困住了,我不知道自己做错了什么。这是我的代码:

第一视图控制器

var selectedRow = 0

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedRow = indexPath.row
        self.performSegue(withIdentifier: "indexPath", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "indexPath") {
            let nextVC = segue.destination as! ViewController3
            nextVC.mySelectedRow = selectedRow
        }

    }

第二视图控制器

    var mySelectedRow = 0

override func viewWillAppear(_ animated: Bool) {
        self.myCollectionView.scrollToItem(at: mySelectedRow, at: .centeredHorizontally, animated: true)
    }

我在这一行收到错误。

self.myCollectionView.scrollToItem(at: mySelectedRow, at: .centeredHorizontally, animated: true)

2 个答案:

答案 0 :(得分:2)

方法scrollToItem(at:at:animated:)希望IndexPath作为第一个参数而不是Int。因此,要么从mySelectedRow实例创建IndexPath对象,要么需要传递IndexPath个对象而不是Int

如果您不知道要在collectionView中滚动的部分,则需要传递indexPath而不是传递行。

第一视图控制器

self.performSegue(withIdentifier: "indexPath", sender: indexPath)


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "indexPath") {
        let nextVC = segue.destination as! ViewController3
        nextVC.mySelectedIndexPath = sender as! IndexPath
    }
}

第二视图控制器

var mySelectedIndexPath = IndexPath()

override func viewWillAppear(_ animated: Bool) {
    self.myCollectionView.scrollToItem(at: mySelectedIndexPath, at: .centeredHorizontally, animated: true)
}

如果您知道要在collectionView中滚动的部分,则只需这样就可以了。

self.myCollectionView.scrollToItem(at: IndexPath(row: mySelectedRow, section: 0), at: .centeredHorizontally, animated: true)

答案 1 :(得分:0)

像这样使用:

self.myCollectionView.scrollToItem(at: IndexPath.init(row: mySelectedRow, section: 0), at: .centeredHorizontally, animated: true)