首页 文章

点击单元格后返回到UICollectionView的相同滚动位置

提问于
浏览
0

我有一个UICollectionView,其中填充了设备照片库中的所有照片 . 点击一个单元格(照片)后,它会切换到允许编辑的视图控制器 . 在此视图中,有一个“添加照片”按钮可将用户返回到UICollectionView(以选择另一张照片) . 我需要滚动位置将前一个拍摄的单元“聚焦”在视图的中心,而不需要任何动画或跳跃 .

我已经尝试将tapped indexPath保存为变量,然后在viewDidAppear上,使用scrollToItemAtIndexPath滚动到该indexPath . 问题是我无法弄清楚如何在单元格点击上更新变量(以保存indexPath) . 我在didSelectItemAtIndexPath中尝试了这个,但是值实际上从未保存过 .

var cellTappedIndexPath = Int()

在didSelectItemAtIndexPath里面:

cellTappedIndexPath = indexPath.row

cellTappedIndexPath的值永远不会保存 .

仅用于测试scrollToItemAtIndexPath,我已将以下内容添加到viewDidAppear:

customViewCollectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 25, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: false)
// 25 is just a number I have set for testing. Ultimately, I would like this to be the saved indexPath of the last tapped cell.

这会导致collectionView在完全加载后“跳转”到单元格25 . 如果我将动画设置为true,则会在顶部加载,然后向下滚动到单元格25.不是我想要的结果 .

我只想在这里做两件事 . 1 - 将单击的单元格保存为变量 . 2 - 使用scrollToItemAtIndexPath(#1中的变量),这样视图就会立即加载,最后一个单元格直接进入中间,没有动画或任何东西 .

如果需要进一步澄清,请与我们联系 . 谢谢!

1 回答

  • 0

    您可以在轻触 collectionview 单元格时保存所选的 indexPath ,并在需要时使用它 .

    var selectedIndexPath: NSIndexPath?
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    
        selectedIndexPath = indexPath
    }
    
    func scrollToCell(){
    
          if let index = selectedIndexPath{
     customViewCollectionView.scrollToItemAtIndexPath(index, atScrollPosition: .CenteredVertically, animated: false)
        }else{
            print("A cell hasnt been selected yet") 
      }
    }
    

相关问题