I have a tableview with the cells having a horizontal collection view. I have multiple cells with the same style. Let's say tableView cells at indices 0 & 5 have the same style (I am using the same UITableViewCell subclass in dequeueReusableCellWithIdentifier).
In short, when I'm re-using tableview cells, the content offset of the scroll view inside the UITableViewCell is being set to the previous re-used cell.
Is there someway I can disable this behaviour, so that each cell maintains it's own offset regardless of any scroll activity on another cell.
You can achieve this by adding the following methods to your custom cell class:
public func setScrollPosition(x: CGFloat) {
collection.setContentOffset(CGPoint(x: x >= 0 ? x : 0, y: 0), animated: false)
}
public func getScrollPosition() -> CGFloat {
return collection.contentOffset.x
}
And the following in your table view data source class:
var offsets = [IndexPath:CGFloat]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.setScrollPosition(x: offsets[indexPath] ?? 0)
return cell
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
offsets[indexPath] = collectionCell.getScrollPosition()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With