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

标签 swift scroll uicollectionview

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

我尝试将点击的indexPath保存为变量,然后在viewDidAppear上,使用scrollToItemAtIndexPath滚动到该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中的变量),这样 View 就会立即加载,最后一个单元格直接点击到中间,没有动画或任何东西。

如果需要进一步说明,请告诉我。谢谢!

最佳答案

您可以保存点击 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") 
  }
}

关于swift - 点击单元格后返回到 UICollectionView 的相同滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38034315/

相关文章:

flutter - 如何通过 flutter 中的导航栏为单页 Web 应用程序实现动态滚动?

javascript - 使用 React JS 检测固定高度 div 的滚动结束

android - 如何在android中实现图片 ScrollView ?

swift - 根据请求异步加载图像

带有collectionview subview 的ios uiviewcontroller不显示单元格

swift - 将 Java 三部分 for 循环转换为 Swift

swift - 当玩家节点与另一个节点碰撞时游戏结束,当游戏只应在玩家与边界碰撞时结束

objective-c - 忽略了在 ios 8 上工作的 iOs 7 的约束

ios - Swift 无法从 JSON api 读取普通话?

swift - 在 Swift 中定义之前可见的全局变量