首页 > 解决方案 > 在 uitableviewcell xib 中的 uicollectionview 中将图像设置为 imageview

问题描述

我已经采取了一个UITableView和 deque 一个UITableViewCellXIB 并将数据设置为其中的一个标签,我UICollectionViewUITableViewCellXIB 中也有我必须在一个UICollectionViewCell.

UIImageView 在 UICollectionViewCell 中,而相应的 UICollectionView 在 UITableViewCell 中,那么如何将图像设置为该 UIImageView?

在一个文件中也有 tableview 委托功能

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.discoverData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "discoveryTableViewCell", for: indexPath) as! discoveryTableViewCell
    let data = discoverData[indexPath.row]
    cell.messageLbl.text = (data["content"] as! String)

    // This how normally image is set in tableview, how to do with collectionview
    cell.userImage.pin_updateWithProgress = true
    let riderImage = URL(string: (data["profile_pic"] as! String))
    cell.userImage.pin_setImage(from: riderImage, placeholderImage: nil, completion: nil)
    return cell
}

UITableViewCell 中的集合视图委托函数。

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "discoverCell", for: indexPath as IndexPath) as! discoverCollectionViewCell
    cell.postImage.backgroundColor = .cyan
    return cell
}

这是一张黄色框是 UICollectionView 和青色框是 UIImageView 的图片。

在此处输入图像描述

标签: swiftuitableviewuicollectionview

解决方案


cellForRowAt indexPath

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "discoveryTableViewCell", for: indexPath) as! discoveryTableViewCell
    if let data = discoverData[indexPath.row] as? [String: Any] {
        cell.messageLbl.text = (data["content"] as! String)

        cell.data = data
    }
    return cell
}

在您的“discoveryTableViewCell”(应该是“DiscoveryTableViewCell”)中:

var data: [String: Any] {
    didSet {
        collectionView.reloadData()
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "discoverCell", for: indexPath as IndexPath) as! discoverCollectionViewCell

    if let profilePic = data["profile_pic"] as? String {
        let riderImage = URL(string: profilePic)
        cell.postImage.pin_setImage(from: riderImage, placeholderImage: nil, completion: nil)
    }

    return cell
}

您应该遵循 Swift 中正确的样式指南和命名约定。请检查此 URL 以获得更好的理解:


推荐阅读