简体   繁体   English

iOS Swift:如何准备一个单元以供重用

[英]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. 我有一个带有自定义单元格的UITableView,每个单元格都包含一个水平滚动的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 自定义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. 将代码重置为UICollectionViewCell的滚动位置的最佳位置是prepareForReuse方法。 Override it in your cell subclass and it will be called every time a previously existing cell is dequeued by dequeueReusableCellWithReuseIdentifier . 在您的单元子类中重写它,并且每当先前存在的单元格由dequeueReusableCellWithReuseIdentifier出列时,它将被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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