【发布时间】:2025-12-22 19:15:07
【问题描述】:
我正在制作一个购物应用,但遇到了问题。
到目前为止,我一直在解析 json,制作了一个 tableview 单元格,但我遇到了一个错误,它说超出范围:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "hello", for: indexPath) as! DisplayShopTableCellTableViewCell
// Configure the cell...
cell.userLbl.text = namee[indexPath.row] //Index out of range
cell.passLbl.text = myprice[indexPath.row]
let imagedata = try! Data(contentsOf: mySecond[indexPath.row].imageUrl!)
cell.tablecellimageview.image = UIImage(data: imagedata)
return cell
}
这是我的展示店表格单元格:
class DisplayShopTableCellTableViewCell: UITableViewCell {
@IBOutlet weak var userLbl: UILabel!
@IBOutlet weak var passLbl: UILabel!
@IBOutlet weak var tablecellimageview: UIImageView!
解析
func extracted(){
guard let url = URL(string: "http://rajeshrmohan.com/sport.json")
else {
return
}
let task = URLSession.shared.dataTask(with: url){
(data,response,error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
do {
let decoder = JSONDecoder()
let model = try decoder.decode(FullClothes.self, from: dataResponse)
//print(model)
for i in 0..<model.item.count{
self.namee.append(model.item[i].name!)
self.myprice.append(String(model.item[i].price!))
self.myphoto.append(model.item[i].image!)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
【问题讨论】:
-
cellForRowAt委托方法下编写的代码不太合理。为什么要使用两个单独的数组来制作单元格? -
存储数据并用于上面的解析没有?