gpt4 book ai didi

swift - 在 Swift 中迭代并将图像和标题从数组 (image_url) 加载到 ViewController 中的正确方法

转载 作者:行者123 更新时间:2023-11-30 10:33:04 25 4
gpt4 key购买 nike

我在原型(prototype)单元中使用 CollectionView 和 ImageView。我检索API结果(标题和image_url),我想通过数组在 Collection View 中显示图像和标题以检索标题和image_url。

是否可以检索 image_url 并在 CollectionView 中显示图像?

我使用 SwiftyJSON 创建数组,我可以检索数组中的 API 结果(包括标题和 image_url)(可以指出结果)。但我无法在 Collection View 中显示它。

最佳答案

我针对您的问题发布了一个示例代码,可能会对您有所帮助。

//从 API 检索的数组

let titleAndImageArray = []()

//CollectionView数据源方法

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return titleAndImageArray.count
}



func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:YourCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! YourCollectionViewCell
let labelTitle = titleAndImageArray[indexPath.row].title
let musicImageUrlString = titleAndImageArray[indexPath.row].image_url
cell.yourLabelOutletName.text = labelTitle
loadImage(indexPath: indexPath, cell: cell, urlString:musicImageUrlString)
}

*我创建了一个 loadImage 函数来从 URL 获取图像,该函数使用异步图像下载器 SDWebImage 库 SDWebImage *

  func loadImage(indexPath:IndexPath,cell:YourCollectionViewCell,urlString:String){
cell.yourImageViewOutletName.sd_setImage(with: URL(string: urlString), placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in

})
}

关于swift - 在 Swift 中迭代并将图像和标题从数组 (image_url) 加载到 ViewController 中的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58680612/

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