Пользовательская ячейка с UITableView внутри UICollectionViewCell - PullRequest
0 голосов
/ 27 августа 2018

У меня есть пользовательский UICollectionViewCell для UICollectionView. Я пометил этот пользовательский класс как UITableViewDataSource и UITableViewDelegate, чтобы поместить UITableView в каждую ячейку представления Collection.

Представление таблицы отображается правильно в каждой ячейке представления коллекции, но проблема заключается в данных в этих заголовке и ячейках представления таблицы.

Пример: у меня 10 вопросов с 5-6 вариантами ответов на каждый вопрос. Я сохранил количество элементов в представлении коллекции как счетчик QuestionList, который создает правильное количество ячеек представления коллекции

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

Когда я создаю каждую ячейку, как показано ниже:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! QuestionCell

        return cell
    }

Пользовательская ячейка (QuestionCell) отображается правильно, но все настраиваемые ячейки представления коллекции отображают только первый вопрос с его параметрами. Вопрос, который у меня возникает, заключается в том, как связать indexPath.item каждой ячейки представления коллекции с indexPath ячейки TableView внутри класса QuestionCell.

fileprivate func setUpViews(){
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(QuestionHeader.self, forHeaderFooterViewReuseIdentifier: headerId)
        tableView.register(OptionCell.self, forCellReuseIdentifier: cellId)
    }

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerId) as! QuestionHeader

    header.nameLabel.text = questionList[section].questionText

    return header
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


    return questionList[section].options.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! OptionCell

    cell.nameLabel.text = questionList[indexPath.row].options[indexPath.row].optionText

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 50.0
}

Любая идея продолжить это будет высоко оценена.

Ответы [ 3 ]

0 голосов
/ 28 августа 2018

Должен ли только один вопрос из списка вопросов передаваться в вашу группу вопросов, а не весь список? В вашем QuestionCell это должно выглядеть так:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerId) as! QuestionHeader

    header.nameLabel.text = question.questionText

    return header
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


    return question.options.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! OptionCell

    cell.nameLabel.text = question.options[indexPath.row].optionText

    return cell
}
0 голосов
/ 29 августа 2018

Мне удалось решить эту проблему, определив переменную IndexPath в отдельном классе Swift и установив ее значение в функции cellForItem CollectionView. Благодаря такому подходу я смог ссылаться на indexPath каждой ячейки CollectionView внутри соответствующей TableViewCell.

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

  cellIndex = indexPath.item

    print("Cell index: ",cellIndex)
    if indexPath.item > 0{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! PageCell
        cell.tableView.reloadData()
        return cell
    }
    else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! PageCell
        cell.tableView.reloadData()
        return cell
    }

}
0 голосов
/ 28 августа 2018

Я думаю, что вопросник [раздел] .options.count должен измениться.

Вы хотите задать список вопросов в каждой ячейке представления коллекции, верно?

, чем использовать indexPath collectionView в качестве индекса questionList, а не раздела tableView

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return questionList[section].options.count
}
...