ios - UITableViewCell 中的 ScrollView 不会保存位置

标签 ios swift uitableview uicollectionviewcell

我的 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/

相关文章:

ios - 获取 SIGABRT 错误

ios - 滚动时自定义表格未正确显示

iphone - 将 UIScrollView 手势识别器添加到另一个 UIScrollView

iPhone 5 的 iOS 按钮定位

iOS 12.2 : CMMotionManager is blocking the main thread

ios - Swift 中等效的 android.content.BroadcastReceiver

Swift NSMutableURLRequest URLSession 回调未被调用

swift - 有没有办法访问当前语言使用的零?

objective-c - 在表格 View 中的同一行上多次点击

javascript - 从 JavaScript 从 WKWebView 中的 iOS tmp/文件夹加载图像文件