我正在尝试传递用户点击的单元格的 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/