在collectionview中打印模型值


class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var liveModel = [LiveModel]()
@IBOutlet weak var myCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return liveModel.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
cell.imageViewer.image = UIImage(named: "(liveModel[indexPath.row].image[0].src)")
return cell
}
}
struct LiveModel: Codable {
var id: Int
var name: String
var image: [Image]
}
struct Image: Codable {
var id: Int
var name: Int
var src: String
}

我有这个模型。我想访问";src";值从";图像";用于使用indexpath的集合视图。我该怎么做?

我正在从API获取图像。我用模型做那个。我成功地访问了值"0";id""name";从";LiveModel";但我不明白如何访问";src";值从";图像";型号

假设你只想显示第一个图像,并且假设总是至少有一个图像,那么你的行:

cell.imageViewer.image = UIImage(named: "(liveModel[indexPath.row].image[0].src)")

接近。只需删除不必要的字符串插值。

cell.imageViewer.image = UIImage(named: liveModel[indexPath.row].image[0].src)

如果给定的liveModel记录没有图像,则此代码将崩溃。因此,如果这是可能的,你应该相应地编码。

还要注意,对于UICollectionView,您应该使用IndexPathitem属性。将row用于UITableView。尽管实际上它们是一样的。

以下是包含所有更改的更新方法。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
if let imageSrc = liveMode[indexPath.item].image.first?.src {
cell.imageViewer.image = UIImage(named: imageSrc)
}
return cell
}

最新更新