{
"YASSINIRLA" : "True",
"KARBON" : "98",
"GRUP" : "Orta Boy",
"INDIRIMORANI" : "0",
"KLIMA_TR" : "Var",
"KREDI_FIYAT" : "107",
"SIRANO" : "1",
"YAKIT_EN" : "Diesel",
}
您好。我解决了这个问题但是时间太长了。我为他们创建了一个数组。我也在表格视图中展示了它。我怎样才能缩短它?对不起我的英语不好。感谢。
dizi1.append(arac["YASSINIRLA"].string!)
dizi2.append(arac["KARBON"].string!)
dizi3.append(arac["INDIRIMORANI"].string!)
dizi4.append(arac["KLIMA_TR"].string!)
dizi5.append(arac["KREDI_FIYAT"].string!)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return diziAracModelii.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "sonAracListelee") as! sonAracListeleViewCell
cell.lblAracAdi1.text = dizi1[indexPath.row]
cell.lblAracAdi2.text = dizi2[indexPath.row]
cell.lblAracAdi3.text = dizi3[indexPath.row]
cell.lblAracAdi4.text = dizi4[indexPath.row]
cell.lblAracAdi5.text = dizi5[indexPath.row]
return cell
}
答案 0 :(得分:1)
更容易做的是创建一个结构模型,在其中声明变量。然后,您可以创建一个启动器函数,您可以使用json对象中的数据启动变量。我建议在执行此操作时使用SwiftyJSON。
如果让我们在init函数中确保检查对象是否包含任何值。
struct CustomModel {
public private(set) var yassinirla: String?
public private(set) var karbon: String?
public private(set) var indirimorani: String?
public private(set) var klimaTr: String?
public private(set) var krediFiyat: String?
init(arac: JSON) {
if let yassinirla = arac["YASSINIRLA"].string {
self.yassinirla = yassinirla
}
if let karbon = arac["KARBON"].string {
self.karbon = karbon
}
if let indirimorani = arac["INDIRIMORANI"].string {
self.indirimorani = indirimorani
}
if let klimaTr = arac["KLIMA_TR"].string else {
self.klimaTr = klima_tr
}
if let krediFiyat = arac["KREDI_FIYAT"].string else {
self.krediFiyat = krediFiyat
}
}
}
在标题中,您可以将数组diziAracModelii声明为[CustomModel],这样您就不必为每个字符串使用单独的数组。这只是不好的做法。您可以使用单个数组处理此问题。
diziAracModelii: [CustomModel] = [CustomModel]()
func grabJson() {
//...Download the json into a json constant
//Send in the jsonobject in the CustomModel
let newObject = CustomModel(arac: json)
//Append to your string and make sure to reload the tableView data.
diziAracModelii.append(newObject)
self.yourTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return diziAracModelii.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "sonAracListelee") as sonAracListeleViewCell else { return UITableViewCell() }
cell.lblAracAdi1.text = diziAracModelii[indexPath.row].yassinirla
cell.lblAracAdi2.text = diziAracModelii[indexPath.row].karbon
cell.lblAracAdi3.text = diziAracModelii[indexPath.row].indirimorani
cell.lblAracAdi4.text = diziAracModelii[indexPath.row].klimaTr
cell.lblAracAdi5.text = diziAracModelii[indexPath.row].krediFiyat
return cell
}