ios - 在 Collection View 之间传递 indexPath

标签 ios swift uicollectionview swift3

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

第一个 View Controller

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
        }

    }

第二个 View Controller

    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)

最佳答案

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

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

第一个 View Controller

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
    }
}

第二个 View Controller

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)

关于ios - 在 Collection View 之间传递 indexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41397564/

相关文章:

ios - 当我使用 SKPhysicsBody(纹理 :size:) to create physics body I got an issue

ios - 如何在ios中获取一个部分的行数

ios - UICollectionViewCell 背景图像超出单元格

iphone - 我想在iOS中模仿Photoshop图层 'soft light'混合

ios - Horizo​​ntalBarChart 值突出显示

ios - 缩放弹跳 + 导航栏后退按钮点击 = 应用程序崩溃

arrays - 按对象 INT 快速过滤对象数组!属性(property)

ios - Swift 中的子类 NSMutableData

objective-c - 在通用应用程序中使用 UICollectionView

ios - iOS 8-滚动不起作用