Отображать тот же контент в UITableView, включенный в пользовательский UITableViewCell
У меня есть проблема с UITableView, вставленным в UITableViewCell. Это моя пользовательская ячейка:Все отлично работает для первой, второй и третьей ячеек, но из четвертой ячейки для содержимого UITableView, вставленного в ячейку, всегда используются одни и те же строки первой, второй и третьей ячеек. Вместо этого метки вне UITableView правильно отображаются в каждой ячейке. Это мой код для пользовательского класса ячеек:
import UIKit
class SimulazioneQuestionTableViewCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {
let cellIdentifier = "simRisposteCell"
var arrayRisposte = [Risposta]()
@IBOutlet var numeroLabel: UILabel!
@IBOutlet var domandaLabel: UILabel!
@IBOutlet var risposteTableView: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
var nib = UINib(nibName: "SimulazioneQuestionAnswerTableViewCell", bundle: nil)
self.risposteTableView.registerNib(nib, forCellReuseIdentifier: self.cellIdentifier)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayRisposte.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as SimulazioneQuestionAnswerTableViewCell
cell.textLabel?.text = arrayRisposte[indexPath.row].testo
return cell
}
}
И это мой вид контроллера:
import UIKit
class SimulazioneViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var areaSimulazione: Int = Int()
var arrayDomande = [Domanda]()
var arrayRisposte = [[Risposta]]()
var cellIdentifier = "domandaSimulazioneCell"
@IBOutlet var tempoTrascorso: UILabel!
@IBOutlet var simulazioneTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
arrayDomande = ModelManager.instance.getSimulazione(area: areaSimulazione)
var nib = UINib(nibName: "SimulazioneQuestionTableViewCell", bundle: nil)
self.simulazioneTableView.registerNib(nib, forCellReuseIdentifier: self.cellIdentifier)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayDomande.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: SimulazioneQuestionTableViewCell = simulazioneTableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as SimulazioneQuestionTableViewCell
var domanda: Domanda = arrayDomande[indexPath.row]
var rispXDomanda = ModelManager.instance.getAnswersForQuestion(domanda.numero)
cell.numeroLabel.text = String(domanda.numero)
cell.domandaLabel.text = domanda.testo
cell.arrayRisposte = rispXDomanda
return cell
}
Несколько советов, чтобы решить эту проблему?
Спасибо вам, ребята!
1 ответ
У меня никогда не было идеи поставить UITableView
внутри UITableViewCell
и поэтому подошли бы к этому с другой стороны. Я не говорю, что таблица внутри ячейки невозможна или плохая идея, но следующий подход может быть проще.
Насколько я понимаю, в вашем табличном представлении показано несколько вопросов, и на каждый вопрос можно найти ответ прямо под ним.
Я бы использовал один раздел на вопрос, а в первой строке была использована пользовательская ячейка, которая показывает numeroLabel
и domandaLabel
(в принципе SimulazioneQuestionTableViewCell
без таблицы), а затем поместите ответы в оставшиеся строки для раздела.
private let QuestionCellIdentifier = "QuestionCell"
private let AnswerCellIdentifier = "AnswerCell"
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return arrayDomande.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let rispXDomanda = ModelManager.instance.getAnswersForQuestion(domanda.numero)
return 1 + rispXDomanda.count // one extra for the question
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let domanda = arrayDomande[indexPath.section]
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier(QuestionCellIdentifier) as SimulazioneQuestionTableViewCell
cell.numeroLabel.text = String(domanda.numero)
cell.domandaLabel.text = domanda.testo
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier(AnswerCellIdentifier) as SimulazioneQuestionAnswerTableViewCell
let rispXDomanda = ModelManager.instance.getAnswersForQuestion(domanda.numero)
cell.textLabel?.text = rispXDomanda[indexPath.row - 1].testo
return cell
}
Это может быть хорошей идеей для кэширования ответов, которые вы получаете от ModelManager
, Это зависит от того, как дорого их получить - с кодом выше getAnswersForQuestion()
будет называться много.
Изменить: мне лично нравится .Grouped
стиль для представления таблицы. Использование раздела для каждого вопроса позволит визуально отделить их.