在UICollectionView(或UITableView)swift中循环数据

ran*_*dom 10 uitableview ios uicollectionview swift

我试图让它UICollectionView无限滚动.想法是,当你到达底部的数据阵列时,它重新开始.

我这样做是通过返回一个更大的数字numberOfItemsInSection然后做一个%从数组中获取数据.

这很好,我理解:

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 500
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! PhotoCell

    let index = indexPath.item % photos.count
    let url = photos[index]
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,这是实现此功能的最佳方式吗?我一直在网上无休止地环顾四周,找不到任何关于如何做的其他建议(使用时UICollectionView).

Nat*_*ook 5

你所拥有的一切都很好。另一种选择是构建一个集合来包装数据源数组 ( photos) 并提供对其内容的循环访问:

struct LoopedCollection<Element>: CollectionType {
    let _base: AnyRandomAccessCollection<Element>

    /// Creates a new LoopedCollection that wraps the given collection.
    init<Base: CollectionType where Base.Index: RandomAccessIndexType, Base.Generator.Element == Element>(_ base: Base, withLength length: Int = Int.max) {
        self._base = AnyRandomAccessCollection(base)
        self.endIndex = length
    }

    /// The midpoint of this LoopedCollection, adjusted to match up with
    /// the start of the base collection.
    var startAlignedMidpoint: Int {
        let mid = endIndex / 2
        return mid - mid % numericCast(_base.count)
    }

    // MARK: CollectionType

    let startIndex: Int = 0
    let endIndex: Int

    subscript(index: Int) -> Element {
        precondition(index >= 0, "Index must not be negative.")
        let adjustedIndex = numericCast(index) % _base.count
        return _base[_base.startIndex.advancedBy(adjustedIndex)]
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在photos数组旁边声明此循环集合:

let photos: [NSURL] = ...
lazy var loopedPhotos: LoopedCollection<NSURL> = LoopedCollection(self.photos)
Run Code Online (Sandbox Code Playgroud)

然后您最终可以将集合视图方法转换为在循环集合上更通用,或者直接使用循环集合:

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return loopedPhotos.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! PhotoCell

    let url = loopedPhotos[index]
}
Run Code Online (Sandbox Code Playgroud)