创建模型时遇到问题。
我的api是这样的。
{data:["name":"seena","option":["Yes, always","no"]]}
因此,据此我需要使用mvvm方式在tableviewsection中显示数据。
这里我需要两个创建两个模型 1.问题清单 2.选项列表
mymodel:-
class QuestionListModel: NSObject {
var home:[OPTIONS] = []
var id:Int!
var question:String!
var options:[String]?
var v:String?
init(dictionary :JSONDictionary) {
guard let question = dictionary["question"] as? String,
let id = dictionary["id"] as? Int
else {
return
}
if let options = dictionary["options"] as? [String]{
print(options)
print(options)
}
self.question = question
self.id = id
}
}
在视图模型中:-
func numberOfSections(tableView: UITableView) -> Int{
print((datasourceModel.dataListArray?.count)!)
return (datasourceModel.dataListArray?.count)!
}
func titleForHeaderInSection(atsection section: Int) -> QuestionListModel {
return datasourceModel.dataListArray![section]
}
func numberOfRowsInSection(section:Int) -> Int {
print(self.tableArray[section].count)
return self.tableArray[section].count
}
,并且在viewcontroller中为:-
func numberOfSections(in tableView: UITableView) -> Int {
return reviewViewModel.numberOfSections(tableView: tableView)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// let headercell = Bundle.main.loadNibNamed("HeaderCell", owner: self, options: nil)?.first as! questionheader
let identifier = "HeaderCell"
var headercell: questionheader! = tableView.dequeueReusableCell(withIdentifier: identifier) as? questionheader
if headercell == nil {
tableView.register(UINib(nibName: "questionheader", bundle: nil), forCellReuseIdentifier: identifier)
headercell = tableView.dequeueReusableCell(withIdentifier: identifier) as? questionheader
}
headercell.setReviewData(reviews:reviewViewModel.titleForHeaderInSection(atsection:section))
return headercell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 63
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 2
//return 1
return reviewViewModel.numberOfRowsInSection(section: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "Cell"
var cell: QuestionListCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? NH_QuestionListCell
if cell == nil {
tableView.register(UINib(nibName: "NH_QuestionListCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? QuestionListCell
}
cell.contentView.backgroundColor = UIColor.clear
print(reviewViewModel.tableArray)
if (reviewViewModel.type == "1"){
cell.imagebutton.setImage(UIImage(named: "radio_uncheck.png"), for: .normal)
}
else{
cell.imagebutton.setImage(UIImage(named: "radio_uncheck.png"), for: .normal)
}
if let tempArray = reviewViewModel.tableArray[indexPath.section] as? [String] {
print(tempArray)
let values = tempArray[indexPath.row]
print(values)
cell.question.text = values
}
return cell
}
以及如何在tableviewcell中显示选项的数据