【发布时间】:2022-01-08 02:58:12
【问题描述】:
我从 api 收到 json 数据,完全不知道接下来应该怎么做才能将这些数据传递给带有 imageView 和标签的自定义单元格,以便更新 tableView 中的 UI。
获取 JSON
import Foundation
struct Breed: Codable {
let name: String?
let origin: String?
let life_span:String?
let temperament: String?
let description: String?
let wikipedia_url: String?
let image: Image?
}
struct Image: Codable {
let url: String?
}
func getDataFromCatsApi() {
let url = URL(string: "https://api.thecatapi.com/v1/breeds")
let task = URLSession.shared.dataTask(with: url!) { data, _ , error in
let decoder = JSONDecoder()
if let data = data {
let breed = try? decoder.decode([Breed].self, from: data)
print (breed as Any)
} else {
print (error as Any)
}
}
task.resume()
}
所有数据都打印正确。
在 ViewController 中,我有一个带有自定义单元格的 tableView。
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = "Cats"
view.backgroundColor = .systemBackground
getDataFromCatsApi()
}
}
extension MainVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath) as? CustomTableViewCell
return cell ?? CustomTableViewCell()
}
}
自定义单元格的类。这里我有用于显示来自 json 数据的 imageView 和标签。
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var catImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var originLabel: UILabel!
@IBOutlet weak var addToFavButton: UIButton!
}
【问题讨论】:
标签: ios json swift xcode uitableview