【问题标题】:UICollectionViewCell embedded in UITableViewCell changes scroll position when re-appears嵌入在 UITableViewCell 中的 UICollectionViewCell 重新出现时会更改滚动位置
【发布时间】:2017-01-31 01:06:37
【问题描述】:
我有一个表格视图,其中的单元格具有水平集合视图。我有多个具有相同样式的单元格。假设索引 0 和 5 处的 tableView 单元格具有相同的样式(我在 dequeueReusableCellWithIdentifier 中使用相同的 UITableViewCell 子类)。
- 用户滚动到索引 5 处的 tableViewCell。他向左滚动水平集合视图(假设红色 1 和黄色 2 单元格现在被隐藏,青色 3 位于最左边)。
- 用户滚动回到索引 0 处的 tableViewCell。虽然它是不同的 UITableViewCell 实例,但集合视图偏移设置为与索引 5 处的单元格相同。
简而言之,当我重用 tableview 单元格时,UITableViewCell 内滚动视图的内容偏移量被设置为之前重用的单元格。
有没有办法我可以禁用此行为,以便每个单元格保持自己的偏移量,而不管另一个单元格上的任何滚动活动。
【问题讨论】:
标签:
ios
uitableview
uiscrollview
uicollectionview
【解决方案1】:
您可以通过将以下方法添加到自定义单元格类中来实现此目的:
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()
}
【解决方案2】:
您可以设置您的单元格以确认 UIScrollViewDelegate 并实现 scrollViewDidEndDecelerating 方法来保存滚动偏移量,然后当您在 UITableView 的 cellForRowAtIndexPath 中将单元格出列时使用该偏移量来恢复原始偏移量。