gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:53:25 25 4
gpt4 key购买 nike

我有一个表格 View ,其中的单元格具有水平 Collection View 。我有多个具有相同样式的单元格。假设索引 0 和 5 处的 tableView 单元格具有相同的样式(我在 dequeueReusableCellWithIdentifier 中使用相同的 UITableViewCell 子类)。

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

enter image description here

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

有什么办法可以禁用此行为,以便每个单元格都保持其自己的偏移量,而不管另一个单元格上的任何滚动事件。

最佳答案

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

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
}

以及 TableView 数据源类中的以下内容:

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

关于ios - UITableViewCell中嵌入的UICollectionViewCell在重新出现时改变滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39639292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com