I have a UITableView with a custom cell, each of which contains a horizontally scrolling UICollectionView. When the table view cells are recycled the horizontal scroll position of the collection view is recycled with it. Should I be resetting the collection view scroll position manually when I create new cells? And if so is there a way to preserve the scroll position on a per-cell basis?
Custom UITableViewCell
class CustomCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var collectionView:UICollectionView!
var layout = UICollectionViewFlowLayout()
var collectionData = [UIImage]()
let kCellIdentifier = "Cell"
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
layout.minimumLineSpacing = 10.0
layout.minimumInteritemSpacing = 1.0
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.registerClass(ItemCell.self, forCellWithReuseIdentifier: kCellIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
addSubview(collectionView)
}
override func layoutSubviews() {
super.layoutSubviews()
layout.itemSize = CGSize(width: 800, height: bounds.height)
collectionView.frame = bounds
}
}
extension ProjectCell: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kCellIdentifier, forIndexPath: indexPath) as! ItemCell
//Reset collectionView scroll position?
return cell
}
}
The best place to put the code to reset the scroll position in the UICollectionViewCell would be in the prepareForReuse method. Override it in your cell subclass and it will be called every time a previously existing cell is dequeued by dequeueReusableCellWithReuseIdentifier.
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