嵌入在UITableViewCell中的UICollectionViewCell在重新出现时更改滚动位置

Rau*_*nak 6 uitableview uiscrollview ios uicollectionview

我有一个带有水平集合视图的单元格的tableview.我有多个具有相同风格的单元格.假设索引0和5处的tableView单元格具有相同的样式(我在dequeueReusableCellWithIdentifier中使用相同的UITableViewCell子类).

  1. 用户在索引5处滚动到tableViewCell.他向左滚动水平集合视图(假设现在隐藏了red-1和yellow-2单元格,而最左边的是cyan-3).
  2. 用户在索引0处滚动回tableViewCell.虽然它是一个不同的UITableViewCell实例,但集合视图偏移设置为与索引5处的单元格相同.

在此输入图像描述

简而言之,当我重新使用tableview单元格时,UITableViewCell内部滚动视图的内容偏移量被设置为之前重用的单元格.

有一些我可以禁用此行为,以便每个单元格保持它自己的偏移量,无论另一个单元格上的任何滚动活动.

小智 5

您可以通过将以下方法添加到自定义单元格类中来实现此目的:

public func setScrollPosition(x: CGFloat) {
    collection.setContentOffset(CGPoint(x: x >= 0 ? x : 0, y: 0), animated: false)
}

public func getScrollPosition() -> CGFloat {
    return collection.contentOffset.x
}
Run Code Online (Sandbox Code Playgroud)

并在您的表视图数据源类中执行以下操作:

var offsets = [IndexPath:CGFloat]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.setScrollPosition(x: offsets[indexPath] ?? 0)
    return cell
}

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    offsets[indexPath] = collectionCell.getScrollPosition()
}
Run Code Online (Sandbox Code Playgroud)


nis*_*ngh 0

您可以设置单元格以确认 UIScrollViewDelegate 并实现scrollViewDidEndDecelerating 方法来保存滚动偏移量,然后在将单元格从 UITableView 的 cellForRowAtIndexPath 中出队时使用该偏移量恢复原始偏移量。