这是我的json
在下面的三个图像部分,我试图在json
中获得各自的三个图像但是我只能在didselectrowat函数中获取第一张图像。下面是我的代码:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detail = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController
if let urlString = arrdata[indexPath.row].images.first?.src, let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
if let data = data {
detail?.Image = UIImage(data: data)!
}
}.resume()
}
detail?.Name = arrdata[indexPath.row].name
detail?.Name2 = arrdata[indexPath.row].name
detail?.SH_desc = arrdata[indexPath.row].categories.first!.type
detail?.Desc = arrdata[indexPath.row].description
detail?.Price = arrdata[indexPath.row].price
if let urlString = arrdata[indexPath.row].images.first?.src, let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
if let data = data {
detail?.Img1 = UIImage(data: data)!
}
}.resume()
}
if let urlString = arrdata[indexPath.row].images.first?.src, let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
if let data = data {
detail?.Img2 = UIImage(data: data)!
}
}.resume()
}
if let urlString = arrdata[indexPath.row].images.first?.src, let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
if let data = data {
detail?.Img3 = UIImage(data: data)!
}
}.resume()
}
self.navigationController?.pushViewController(detail!, animated: true)
}
请帮帮我…提前感谢!
问题是您总是在搜索images
数组中的第一张图像。
您应该使用索引来检索正确的图像:
试着这样修改你的代码:
let imagesArray = arrdata[indexPath.row].images
if imagesArray.count > 0, let url = URL(string: imagesArray[0].src) {
URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
if let data = data {
detail?.Img1 = UIImage(data: data)!
}
}.resume()
}
if imagesArray.count > 1, let url = URL(string: imagesArray[1].src) {
URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
if let data = data {
detail?.Img2 = UIImage(data: data)!
}
}.resume()
}
if imagesArray.count > 2, let url = URL(string: imagesArray[2].src) {
URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
if let data = data {
detail?.Img3 = UIImage(data: data)!
}
}.resume()
}