gpt4 book ai didi

JSON 数据未传递到 tableView Cell

转载 作者:行者123 更新时间:2023-11-30 11:56:46 25 4
gpt4 key购买 nike

我正在尝试获取以下代码以将 JSON 数据传递到表 viewCell。我已确认 JSON 数据已被捕获并存储在变量 downloadLenderRates 中。但我无法将值传递给 tabelView 单元格。我确认单元格标识符的命名正确,并且帮助管理 tableView 单元格的 swift 文件命名正确。此时,当我运行应用程序时,我没有收到任何错误消息,只有一个空白表。我不知道为什么!

class MortgageRatesVC: UIViewController, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

let mortgousURL = URL(string:"http://mortgous.com/JSON/currentRatesJSON.php")!
var lenderRates = [LenderRate]()

override func viewDidLoad() {
super.viewDidLoad()

downloadJason()

}

func downloadJason () {
lenderRates = []


// guard let downloadURL = url else { return }
URLSession.shared.dataTask(with: mortgousURL) { data, urlResponse, error in
guard let data = data else { return }
do {
let dateFormat = DateFormatter()
dateFormat.locale = Locale(identifier: "en_US_POSIX")
dateFormat.dateFormat = "yyyy-MM-dd"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormat)
let downloadLenderRates = try decoder.decode([LenderRate].self, from: data)

// print(downloadLenderRates)

self.lenderRates = downloadLenderRates

DispatchQueue.main.async {
self.tableView.reloadData()
}

} catch {
print(error)
}
}.resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return lenderRates.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LenderCell") as? LenderCell else { return UITableViewCell() }

cell.lenderNamelbl.text = lenderRates[indexPath.row].financialInstitution
print(lenderRates[indexPath.row].financialInstitution)

return cell

}

}

最佳答案

语法

guard let cell = tableView.dequeueReusableCell(withIdentifier: "LenderCell") as? LenderCell else { 
return UITableViewCell()
}

这是非常不好的习惯。

仅当存在设计错误(例如,如果开发人员忘记将单元格的类设置为自定义类)时,guard 才会失败。在这种情况下,您将在表格 View 中看不到任何内容。

这是建议强制展开的少数情况之一。如果设计设置正确,则单元有效并且其类型是自定义类。进一步始终使用返回非可选单元格的 API dequeueReusableCell(withIdentifier:for:)

let cell = tableView.dequeueReusableCell(withIdentifier: "LenderCell", for: indexPath) as! LenderCell

关于JSON 数据未传递到 tableView Cell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com