gpt4 book ai didi

ios - 如何在 Swift 中的 tableview 自定义单元格上显示 JSON 图像?

转载 作者:行者123 更新时间:2023-11-29 05:45:31 24 4
gpt4 key购买 nike

我是编码新手,正在学习如何将 JSON 图像解析为 TableView 能够显示标签,但无法显示图像文件。如何显示呢?我使用了下面给出的代码,请检查它。

import UIKit

class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {

var dataArray = [[String:AnyObject]]()

@IBOutlet weak var myTable: UITableView!

override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://jsonplaceholder.typicode.com/photos")! //change the url
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "GET" //set http method as POST
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}

guard let data = data else {
return
}

do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:Any]] {

self.dataArray = json as [[String : AnyObject]]
DispatchQueue.main.async {
self.myTable.reloadData()
}
print(json)
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id") as! ModTableViewCell
cell.labout.text = String(describing: dataArray[indexPath.row]["id"]!)
cell.imagethum.image = UIImage(named :dataArray[indexPath.row]["thumbnailUrl"]! as! String)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "story") as? FinalViewController
var selectedindex = indexPath.row
vc?.jarray = dataArray
vc?.selectedindex1 = selectedindex
self.navigationController?.pushViewController(vc!, animated: true)
}
}

最佳答案

您需要首先下载您的图像。基本的解决办法是:

    if let url = URL(string: "YOUR_URL") {
if let data = try? Data(contentsOf: url) {
cell.imagethum.image = UIImage(data: data)
}
}

要了解更高级的解决方案,请查看 SDWebImage 框架(例如) - 它适合初学者。

关于ios - 如何在 Swift 中的 tableview 自定义单元格上显示 JSON 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56184147/

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