colindunn
colindunn

Reputation: 3163

iOS Swift: How to prepare a cell for reuse

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
    }
}

Upvotes: 3

Views: 6410

Answers (1)

Dima
Dima

Reputation: 23634

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.

Upvotes: 4

Related Questions