我的 UITableView
中有一些 UIScrollView
。
我的问题是,如果我将第一个单元格中的 ScrollView 滚动到另一个位置,第四个单元格也将位于同一位置。
第二个和第五个,第三个和第六个都一样……
有没有办法让单元格中的 ScrollView 保持其位置?
最佳答案
您应该将 UIScrollView
的实际内容偏移量保存在一个数组中,在自定义委托(delegate)中发生滚动后检索该值,并将偏移量设置为 cellForRowAt< 中保存的值
.
CustomCell.swift
weak var delegate: CellScrollViewDelegate?
let scrollView: UIScrollView!
var contentOffset: CGPoint!
func setUpCell() {
scrollView.delegate = self
scrollView.contentOffset = savedContentOffset
}
[...]
func scrollViewDidScroll(_ scrollView: UIScrollView) {
delegate?.horizontalCellDidScroll(indexPath: indexPath, contentOffset: scrollView.contentOffset)
}
TableViewController.swift
var cellScrollContentOffsets = [[CGPoint]]()
func horizontalCellDidScroll(indexPath: IndexPath, contentOffset: CGPoint) {
cellScrollContentOffsets[indexPath.section][indexPath.row] = contentOffset
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath)
cell.delegate = self
cell.savedContentOffset = cellScrollContentOffsets[indexPath.section][indexPath.row]
cell.setUpCell()
return cell
}
Delegate.swift
protocol CellScrollViewDelegate: class {
func horizontalCellDidScroll(indexPath: IndexPath, contentOffset: CGPoint)
}
关于ios - UITableViewCell 中的 ScrollView 不会保存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45439663/