简体   繁体   中英

Why does my UITableView within a UICollectionView within another UITableView doesn't load data when scrolled to it for the first time?

I have a UITableView , one of the cells contains a UICollectionView . Then, each cell of the UICollectionView also contains a UITableView . To make this clearer:

检查下面的图像

The first time I scroll to this cell, nothing is loaded, the height of the cell is simply 0. When I continue to scroll the outer UITableView until this particular cell is off the screen (destroyed) and come back there, the data is then loaded. Here's a simplified code snippet:

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

The special UITableViewCell is defined as follows:

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

Finally, I have this inner UITableView defined as follows:

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
    }

    ...
}

How should I fix this problem? :)

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

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

You should create a flag variable to control someCollectionView and innerTableView , that are just loaded on the first time when you set sectionData and items

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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