Источник данных для CollectionView внутри CollectionViewCell всегда равен нулю - PullRequest
0 голосов
/ 24 февраля 2020

У меня есть UICollectionView внутри UICollectionViewCell и отдельный NSObject, то есть dataSource. Я могу установить dataSource для внешнего UICollectionView, но не для внутреннего.

Вот ячейка, содержащая внутренний UICollectionView:

class FeaturedCell: UICollectionViewCell, UICollectionViewDelegate {

    @IBOutlet var collectionView: UICollectionView!
    let data = FeaturedData()

    override init(frame: CGRect) {
        super.init(frame: frame)
        //setUp()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    func setUp() {
        collectionView.dataSource = data
        collectionView.delegate = self
        collectionView.reloadData()

    }
}

extension FeaturedCell {

    func setCollectionViewDataSourceDelegate <D: FeaturedData> (_ dataSourceDelegate: D, forRow row: Int) {

        collectionView.delegate = dataSourceDelegate
        collectionView.dataSource = dataSourceDelegate

        collectionView.reloadData()
        print("Reload Data")

    }

}

И UIView, содержащий внешний UICollectionView:

class MainView: UIView, UICollectionViewDelegate {

    @IBOutlet var collectionView: UICollectionView!
    let data = MainData()

    override func awakeFromNib() {
        setUp()
    }


    func setUp() {
        collectionView.dataSource = data
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.orange
        collectionView.collectionViewLayout = createLayout()
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.allowsSelection = true
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        print("WillDisplay")
        guard let cell: FeaturedCell = collectionView.dequeueReusableCell(withReuseIdentifier: "FeaturedCell", for: indexPath) as? FeaturedCell else {
            fatalError("Unable to dequeue FeaturedCell.")
        }
        cell.setCollectionViewDataSourceDelegate(featuredData, forRow: indexPath.item)
    }
}

Оба эти метода вызываются, но dataSource и delegates никогда не устанавливаются. Я также точно следовал этому учебнику (даже с UITableView), и он все равно не установил бы dataSource или delegate. Что я делаю неправильно?

Ответы [ 2 ]

0 голосов
/ 24 февраля 2020

Решил это. Проблема заключалась в том, что это:

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    print("WillDisplay")
    guard let cell: FeaturedCell = collectionView.dequeueReusableCell(withReuseIdentifier: "FeaturedCell", for: indexPath) as? FeaturedCell else {
        fatalError("Unable to dequeue FeaturedCell.")
    }
    cell.setCollectionViewDataSourceDelegate(featuredData, forRow: indexPath.item)
}

Необходимо изменить на это:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
print("WillDisplay")
guard let featuredCell = cell as? FeaturedCell else { return }
featuredCell.setCollectionViewDataSourceDelegate(featuredData, forRow: indexPath.item)

}

0 голосов
/ 24 февраля 2020

Я думаю, что это поможет

class FeaturedCell: UICollectionViewCell {

    @IBOutlet var collectionView: UICollectionView!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

}

extension FeaturedCell {

    func setCollectionViewDataSourceDelegate <T: UICollectionViewDelegate , D: FeaturedData> (delegate: T  dataSource: D, forRow row: Int) {

        collectionView.delegate = delegate
        collectionView.dataSource = dataSource

        collectionView.reloadData()
        print("Reload Data")
    }
}

и в MainView

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    print("WillDisplay")
    guard let cell: FeaturedCell = collectionView.dequeueReusableCell(withReuseIdentifier: "FeaturedCell", for: indexPath) as? FeaturedCell else {
        fatalError("Unable to dequeue FeaturedCell.")
    }
    cell.setCollectionViewDataSourceDelegate(self, featuredData, forRow: indexPath.item)
}

И для учебника вы следовали по этой ссылке Github для учебника, сравните ваш код с этим и посмотрите, где вы пропустили.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...