我正在使用Json Object在tableview中显示。我解析Json也成功打印了数据。并且我正在使用foreach语句将数据放入变量中,但是问题是我正在json对象中将变量的最后一项放入变量中。我想显示用户命名变量以在其上显示名称
这是我的Json数据
{
"Categories": [
"school, class"
],
"Tags": [
{
"Value": "ashok",
"Key": "Name"
}, {
"Value": "III",
"Key": "class"
}, {
"Value": "A",
"Key": "section"
}
]
}
这是我的模型数组
struct classInfo: Decodable {
let Categories: String
let Tags: String
let Value: String
let Key: String
var Name: String
let class: String
}
这是我的代码
var ClassList = [classInfo]()
var name: String = ""
var class: String = ""
在JSONSerialization功能中
do{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
print(json as AnyObject)
let cat = json["Categories"] as? [String: Any]
print(cat!)
if let array = json["Tags"] as? [[String: Any]] {
for obj in array {
if let dict = obj as? NSDictionary {
// Now reference the data you need using:
let Value = dict.value(forKey: "Value")
let Key = dict.value(forKey: "Key")
print(Value!)
print(Key!)
self.name = tag["Value"] as! String
print(self.name)
self.class = tag["Value"] as! String
print(self.class)
}
}
}
行功能单元格中的
cell.Name.text = "Name:\(name)"
cell.class.text = "class: \(class)"
答案 0 :(得分:0)
使用此
class ModelClass{ var name:String ; var classs:String }
class ModelDataClass { static var modelData = [ModelClass]() }
在您的viewController中。 -在模型中添加值并 在您的cellForRowAt中->
cell.nameTextLabel.text = ModelDataClass.modelData[indexPath.row].name
cell.classsTextLabel.text = ModelDataClass.modelData[indexPath.row].classs
答案 1 :(得分:0)
嘿,那就试试吧
class ModelClass {var name:String}
现在创建一个自定义tableView单元格
class CustomTableViewCell:UITableViewCell {
var dataModel : ModelClass?{
didSet{
guard let model = dataModel else {return}
print(model.name)
// set label text here : ex := myLabel.text = model.name
}
}
// declare all IBLayouts or create them programmatically... its your choice
}
在您的tableView单元格中(cellForRowAt --->) 使用此代码段
var dataModel = [ModelClass]()
dataModel = [ModelClass(name:"Rishabh"),ModelClass(name:"Adi"),ModelClass(name:"FFFf")]
现在使用
将此dataModel传递给cellDAtaModellet cell = tableView.deq() as! CustomTableViewCell //deq() - > to lazy to type whole lol ;P type by yourself
cell.dataModel = dataModel[indexPath.row]