Scroll View in UITableViewCell won't save position

浪尽此生 提交于 2019-12-13 08:10:55

问题


I have some UIScrollViews in my UITableView.

My problem is that if I scroll the scroll view in the first cell to another position, the fourth cell will also be at that same position.

Same for the second and the fifth, the third and the sixth...

Is there a way for the scroll views in the cells to keep their position?


回答1:


You should save the actual content offsets of your UIScrollViews in an array, retreive the value after a scroll happened in a custom delegate and set the offset to the saved value in 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)
}


来源:https://stackoverflow.com/questions/45439663/scroll-view-in-uitableviewcell-wont-save-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!