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

问题描述 投票:0回答:1

我在原型单元格中将CollectionView与ImageView一起使用。我检索API结果(title和image_url),我想通过数组在集合视图中显示图像和标题,以检索title和image_url。

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

我使用SwiftyJSON创建数组,我可以在数组中检索API结果(包括标题和image_url)(可以列出结果)。但是我无法在集合视图中显示它。

swift swift4 uicollectionviewcell swifty-json
1个回答
0
投票

我正在为您的问题发布示例代码,可能会对您有所帮助。

//从API检索的数组

let titleAndImageArray = []()

// CollectionView DataSourceMethod

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获取图像,该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

    })
}
© www.soinside.com 2019 - 2024. All rights reserved.