首页 > 解决方案 > 为什么第一次滚动到另一个 UITableView 中的 UICollectionView 中的 UITableView 不加载数据?

问题描述

我有一个UITableView,其中一个单元格包含一个UICollectionView. 然后, 的每个单元格UICollectionView也包含一个UITableView. 为了更清楚地说明这一点:

检查下面的图片

我第一次滚动到这个单元格时,什么都没有加载,单元格的高度只是 0。当我继续滚动外部 UITableView 直到这个特定的单元格离开屏幕(被破坏)并回到那里时,数据就是加载。这是一个简化的代码片段:

class ViewController: UIViewController {
    @IBOutlet weak var outerTableView: UITableView!

    func tableView(..., cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == ... {
            // return regularCells
        }

        let cellThatHasCollectionView: CustomTableViewCell = ...

        cellThatHasCollectionView.sectionData = ... // An array of array

        return cellThatHasCollectionView
    }
}

特殊UITableViewCell定义如下:

private class CustomTableViewCell: UITableViewCell {
    private let someCollectionView: UICollectionView = ...

    public var sectionData: [[SomeType]] = []

    init(...) {
        ...
        someCollectionView.delegate = self
        someCollectionView.dataSource = self
    }

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

    func collectionView(..., cellForItemAt indexPath: IndexPath) -> ... {
        let cell: CustomCollectionViewCell = ...
        cell.items = sectionData[indexPath.row]
        return cell
    }
}

最后,我将这个内部UITableView定义如下:

private class CustomCollectionViewCell: UICollectionViewCell {
    public var items: [SomeType] = []

    private let innerTableView: UITableView = ...

    init(...) {
        ...
        innerTableView.delegate = self
        innerTableView.dataSource = self
    }

    func tableView(..., numberOfItemsInSection section) -> Int {
        return items.count
    }

    ...
}

我应该如何解决这个问题?:)

标签: iosswiftuitableviewuicollectionview

解决方案


public var sectionData: [[SomeType]] = []{
    didSet{
        someCollectionView.reloadData()
    }
}

public var items: [SomeType] = []{
    didSet{
        innerTableView.reloadData()
    }
}

您应该创建一个标志变量来控制someCollectionViewand innerTableView,它只是在您第一次设置sectionDataand时加载items


推荐阅读