【问题标题】:Returning to the same scroll position of UICollectionView after tapping a cell点击单元格后返回到 UICollectionView 的相同滚动位置
【发布时间】:2016-06-26 00:57:44
【问题描述】:

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

我尝试将点击的 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 中),这样视图就会立即加载,最后一个单元格直接点击到中间,没有动画或任何东西。

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

【问题讨论】:

  • 对 cellTappedIndexPath 的引用需要保存在某个地方,例如您的 ViewController 的属性。你这样做了吗?
  • 如果animated: true 让它跳跃,那么animated:false 适合你?
  • @Literphor - false 导致不希望的跳转,而 true 导致 collectionView 从顶部开始,然后自动滚动到正确的区域。我只需要在没有任何动画或跳跃的情况下将视图显示在正确的位置。此外,是的,cellTappedIndexPath 被定义为通过 didSelectItem 更新的类级别变量......但是两者都不能正常工作。

标签: swift scroll uicollectionview


【解决方案1】:

您可以在点击collectionview 单元格时保存选定的indexPathreceived,并在需要时使用它。

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

【讨论】:

  • 我添加了 selectedIndexPath 属性,将其添加到 didSelectItem 以更新其值,添加函数,并在 viewDidAppear(和 viewDidLoad / viewWillAppear)中调用函数 scrollToCell。日志不断打印“尚未选择单元格”
猜你喜欢
  • 2013-07-15
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多