У меня есть следующие значения: -
[[yes,no],[yes,no]]
мне нужно отображать в cellForRowAt indexPath в tableview.
мой код: -
var tableArray:Array<[String]> = []
получение данных из JSON: -
if let data = wholedata["data"] as? Array<[String:Any]>{
print(data)
print(response)
for question in data {
let options = question["options"] as! [String]
self.tableArray.append(options)
// self.fetchedHome.append(options as! [home])
self.no = options.count
}
print(self.tableArray)
моя ячейка для строки по индексу в tableview: -
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "Cell"
var cell: QuestionListCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? QuestionListCell
if cell == nil {
tableView.register(UINib(nibName: "QuestionListCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? QuestionListCell
}
print(reviewViewModel.tableArray)
cell.question.text = "hai"
} else {
return UITableViewCell()
}
}
Как отобразить данные в ячейке tableview?





Это очень простой вопрос, братан.
Если вы не против использования раздела, попробуйте это ~ !!!
var tableArray:Array<[String]> = []
func viewDidLoad() {
let table = UITableView()
table.register(YourNib, forCellReuseIdentifier: YourIdentifier)
}
func numberOfSections(in tableView: UITableView) -> Int {
return tableArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableArray[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let tempArray = tableArra[indexPath.section] as? [String],
let cell = tableView.dequeueReusableCell(withIdentifier: YourIdentifier) as? QuestionListCell {
// just Initialize your cell with data in datasource
cell.question.text = tempArray[indexPath.row]
return cell
} else {
return UITableViewCell()
}
}
вот что должно быть YourCustomCell (withData:
вам нужно создать собственный подкласс ячейки UITableViewCell.
Пожалуйста, проверьте, обновил ли я свой мобильный телефон по индексу. Как это сделать?
Я изменил свой ответ, пожалуйста, проверьте его. Я не думаю, что мой код идеально подходит для вашей цели, но я надеюсь, что он вам поможет ~
Вы можете преобразовать array of array в array перед отображением в таблице, и ваш tableViewController будет иметь только array данных.
Вы можете использовать flatmap / compactMap для преобразования array of array в array:
let a = ["yes","no"]
let b = [a, a] // [["yes","no"], ["yes","no"]]
b.flatMap({$0}) // ["yes","no", "yes","no"]
Прежде всего, не регистрируйте ячейку в cellForRow, зарегистрируйте ее в viewDidLoad.
private let identifier = "Cell" // Declare the identifier as private constant on the top level of the class.
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UINib(nibName: "QuestionListCell", bundle: nil), forCellReuseIdentifier: identifier)
// do other stuff
}
Затем в cellForRow получить элемент для пути индекса из массива источника данных. Поскольку параметры представляют собой массив, вы должны отобразить его в виде двух меток или объединить элементы.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as! QuestionListCell
let options = tableArray[indexPath.row]
cell.question.text = options.joined(separator: ", ")
return cell
}
Я думаю, вы хотите отображать больше данных, чем options. Но на данный момент вы заполняете массив источника данных только с помощью options.
Еще раз, как было предложено в моем ответе на один из ваших предыдущих вопросов, я настоятельно рекомендую декодировать JSON в пользовательские структуры. Это делает жизнь намного проще.
как это решить?