UITableViewCell с UITableView не отображается - PullRequest
0 голосов
/ 11 мая 2019

Я пытаюсь создать пользовательский UITableViewCell, который содержит свой собственный TableView.Однако, когда я выполняю приложение, вложенный TableView не будет отображаться вообще.Это не вызов функции делегата, которая возвращает повторно используемую ячейку.optionsList связан с TableView, изображенным ниже.Не уверен, что мешает его появлению на экране.MultiChoiceCell, созданный с помощью файла xib, должен в основном создавать табличное представление с меткой вверху и нижнее представление таблицы, содержащее прокручиваемое табличное представление, которое содержит ячейки просто с меткой, отмеченной галочкой при выборе.

Код в ViewController устанавливает массив параметров со значениями меток, которые необходимо загрузить во вложенное табличное представление с именем optionsList:

class MultipleChoiceViewCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource{
    @IBOutlet weak var surveyQuestionLabel: UILabel!
    @IBOutlet weak var optionsList: UITableView!{
        didSet{
            self.optionsList.delegate = self
            self.optionsList.dataSource = self
            self.optionsList.rowHeight = 45
            let nibOptionCell = UINib(nibName: "SimpleTableCell", bundle: nil)
            self.optionsList.register(nibOptionCell, forCellReuseIdentifier: "SimpleTableCell")
            self.optionsList.reloadData()
        }
    }
    var options = [String](){
        didSet{
            self.optionsList.reloadData()
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let return_cell = tableView.dequeueReusableCell(withIdentifier: "SimpleTableCell", for: indexPath) as! SimpleTableViewCell
        return_cell.optionLabel.text = options[indexPath.row]
        return return_cell
    }

}

enter image description here

Код в ViewController:

    override func viewDidLoad() {
        super.viewDidLoad()

        self.surveyQuestionsTableView.delegate = self
        self.surveyQuestionsTableView.dataSource = self

        self.surveyQuestionsTableView.rowHeight = 285
        let nibFreeResponse = UINib(nibName: "FreeResponseCell", bundle: nil)
        surveyQuestionsTableView.register(nibFreeResponse, forCellReuseIdentifier: "freeResponseCell")

        let nibMultiChoice = UINib(nibName: "MultiChoiceCell", bundle: nil)
        surveyQuestionsTableView.register(nibMultiChoice, forCellReuseIdentifier: "multiChoiceCell")
    }
    //return number of cells to display
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return survey_questions["survey"].count
    }

    //generate cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let survey_question = survey_questions["survey"][indexPath.row]
        if(survey_question["type"] == "freeResponse"){
            let return_cell = tableView.dequeueReusableCell(withIdentifier: "freeResponseCell", for: indexPath) as! FreeResponseViewCell
            return_cell.surveyQuestionLabel.text = survey_question["question"].string!
            return_cell.surveyResponseField.layer.borderWidth = 0.5
            return_cell.surveyResponseField.layer.borderColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)

            return return_cell
        }

        if(survey_question["type"] == "multipleChoice"){
            let return_cell = tableView.dequeueReusableCell(withIdentifier: "multiChoiceCell", for: indexPath) as! MultipleChoiceViewCell
            return_cell.surveyQuestionLabel.text = survey_question["question"].string!
            return_cell.options = survey_question["answers"].arrayObject as! [String]
            DispatchQueue.main.async {
                return_cell.optionsList.reloadData()
            }


            return return_cell
        }

enter image description here

Ответы [ 2 ]

0 голосов
/ 11 мая 2019

Вызов функции настройки из ваших методов init ...

func setUpTable() {
    optionsList.delegate = self
    optionsList.dataSource = self
    optionsList.rowHeight = 45

    // Register your option cell
    let nibOptionCell = UINib(nibName: "AnswerOptionCell", bundle: nil)
        optionsList.register(nibOptionCell, forCellReuseIdentifier: "AnswerOptionCell")

}

Как обычно, снимите флажок AnswerOptionCell.

Рекомендуем оставить идентификаторы повторного использования такими же, как имена классов ячеек, чтобыизбегайте ошибок.

0 голосов
/ 11 мая 2019

Попробуйте позвонить reloadData() в MultipleChoiceViewCell setupTable. Вызовите setupTable() с требуемого init? (Кодировщик aDecoder: NSCoder):

//...

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style , reuseIdentifier: reuseIdentifier)
    setUpTable()
}

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

func setUpTable(){
    self.optionsList.delegate = self
    self.optionsList.dataSource = self
    self.optionsList.rowHeight = 45
    self.addSubview(optionsList)
    self.reloadData()
}

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