简体   繁体   中英

Scroll View in UITableViewCell won't save position

I have some UIScrollView s 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?

You should save the actual content offsets of your UIScrollView s 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM