【问题标题】:How to show the API image using SwiftyJSON如何使用 SwiftyJSON 显示 API 图像
【发布时间】:2020-01-22 17:05:05
【问题描述】:

我想知道如何将 API 图像从 API 显示到 UIImage。我可以从控制台获取结果,但无法将图像从 Internet 显示到集合视图。

public var foodImage = [String]()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MainPageCollectionViewCell
    //Below is fine and it can display food title from Internet
    cell.FoodTitle.text = self.foodTitle[indexPath.item]
    //Cannot display API image from Internet
    cell.Food.image = foodImage[indexPath.item] as? UIImage

    return cell
}

获取API结果的代码如下:

self.foodImage = json["hits"].arrayValue.map {$0["recipe"]["image"].stringValue}
print(self.foodImage)

【问题讨论】:

标签: ios swift swift4 swifty-json collectionview


【解决方案1】:

有一个可可豆荚可用于从 URL 加载图像 click here

将此添加到您的 pod 文件中

pod 'SDWebImage'
import SDWebImage

imageView.sd_setImage(with: URL(string: yourURLString), placeholderImage: UIImage(named: "placeholder.png"))

【讨论】:

  • 我有一个数组来存储图像 URL,我想使用 Collection View 显示它。是否可以使用 SDWebImage?
  • yes @lpy , SDWebImage 仅用于从 URL 下载和显示图像。
  • 我不知道在 SSWebImage 中使用数组的语法。你能举个例子吗?
  • 如果让 cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollVCell", for: indexPath) 为? ImageCollVCell { cell.imgaeView.sd_setImage(with: URL(string: arr[indexPath.row]) return cell }
  • 我添加了 cell.Food.sd_setImage(with: URL(string: foodImage[indexPath.row])),但是发生了错误。 (线程 1:致命错误:索引超出范围)。有什么想法吗?非常感谢。
猜你喜欢
  • 2019-02-02
  • 1970-01-01
  • 2021-11-07
  • 2019-12-04
  • 2020-06-18
  • 2011-07-24
  • 2015-03-24
  • 2014-07-02
  • 2013-06-29
相关资源
最近更新 更多