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

时间:2016-09-22 12:37:57

标签: ios uitableview uiscrollview uicollectionview

我有一个带有水平集合视图的单元格的tableview。我有多个具有相同风格的单元格。让我们说索引0&的tableView单元格。 5具有相同的样式(我在dequeueReusableCellWithIdentifier中使用相同的UITableViewCell子类)。

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

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

    我是否可以禁用此行为,以便每个单元格保持自己的偏移量,无论其他单元格上的任何滚动活动如何。

2 个答案:

答案 0 :(得分: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
}

以下表格中的数据源类:

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

答案 1 :(得分:0)

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

相关问题