我從 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!
}
uj5u.com熱心網友回復:
首先,您沒有從 from 回傳任何內容getDataFromCatsApi().因為它是一個異步呼叫,所以您必須實作一種通過使用回呼或委托來獲取值的方法。在這種情況下,回呼就足夠了。
然后,一旦您從 api 呼叫中收到一個值,請設定func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)您可以使用的那些值cell.nameLabel.text = <received value>等等。
uj5u.com熱心網友回復:
首先,僅將那些屬性宣告為可選項 nil
struct Breed: Decodable {
let name, origin, lifeSpan, temperament, description: String
let wikipediaUrl: String?
let image: Image?
}
struct Image: Decodable {
let url: String?
}
在getDataFromCatsApi添加完成處理程式
func getDataFromCatsApi(completion: @escaping (Result<[Breed],Error>) -> Void ) {
let url = URL(string: "https://api.thecatapi.com/v1/breeds")
let task = URLSession.shared.dataTask(with: url!) { data, _ , error in
if let error = error { completion(.failure(error)); return }
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
completion(Result { try decoder.decode([Breed].self, from: data!) })
}
task.resume()
}
在MainVC宣告一個資料源陣列
var cats = [Breed]()
替換viewDidLoad為
override func viewDidLoad() {
super.viewDidLoad()
title = "Cats"
view.backgroundColor = .systemBackground
getDataFromCatsApi {[unowned self] result in
DispatchQueue.main.async {
switch result {
case .success(let breed):
self.cats = breed
self.tableView.reloadData()
case .failure(let error): print(error)
}
}
}
}
和表視圖資料源方法
extension MainVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cats.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath) as! CustomTableViewCell
let cat = cats[indexPath.row]
cell.nameLabel = cat.name
cell.originLabel = cat.origin
}
}
加載圖片超出了問題的范圍。有像 SDWebImage 或 Kingfisher 這樣的庫可以異步加載和快取影像。
uj5u.com熱心網友回復:
我附上了代碼請檢查
extension MainVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Breed.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath) as? CustomTableViewCell
cell.nameLabel.text = Breed[indexPath.row].name // see here
return cell ?? CustomTableViewCell()
}
}
uj5u.com熱心網友回復:
我正在使用與此類似的結構
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
var Breed: [Breed]!
override func viewDidLoad() {
super.viewDidLoad()
title = "Cats"
view.backgroundColor = .systemBackground
getDataFromCatsApi()
}
}
extension MainVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Breed.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CustomTableViewCell
cell.yourLabelName.text = Breed[indexPath.row].name
return cell
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/371290.html
上一篇:SwiftUI有條件地觸發切換
下一篇:將字串中的元音轉換為大寫
