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

标签 swift swift4 uicollectionviewcell swifty-json

我在原型(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/

相关文章:

ios - 调整 TableView 高度后

swift - Apple TV 上带有 swift 的 .XZ 文件

ios - CollectionViewCell 无法识别的选择器发送到实例

ios - UICollectionViewCell 问题调用方法

swift - Realm 中的嵌套查询。 swift

iOS( swift ): Collection View indexPath(for: cell) is nil for non visible cell

swift 3 DispatchGroup leave 在 helper 类函数中调用时导致崩溃

swift - 限制我的玩家在 x 方向移动太多

swift - 有什么方法可以对数组内的自定义对象进行排序吗?

ios - 使用 geofire 进行一次性位置更新? swift 4