UITableViewCell 中的滚动视图不会保存位置

Scroll View in UITableViewCell won't save position

我的 UITableView 中有一些 UIScrollView

我的问题是,如果我将第一个单元格中的滚动视图滚动到另一个位置,第四个单元格也会在同一位置。

第二个和第五个,第三个和第六个也一样...

有没有办法让单元格中的滚动视图保持其位置?

您应该将 UIScrollView 的实际内容偏移量保存在一个数组中,在自定义委托中发生滚动后检索该值,并将偏移量设置为 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)
}