首页 > 解决方案 > 在集合视图中设置图像和名称 swift 5

问题描述

因此,我试图在集合视图中设置图像及其名称,我实现的是我设置了名称但我无法将图像设置到该集合视图

我在这里设置名称和图标数组

let dataArray = ["Home", "Appointment", "Teleconsultation", "Lab", "Pharmacy", "Registration", "Careers", "Utilities","Feedback"]
    var icons : [UIImage] = [UIImage(named: "appointment.png")!, UIImage(named: "telehealth.png")!, UIImage(named: "lab.png")!, UIImage(named: "pharmacy.png")!, UIImage(named: "labreports.png")!, UIImage(named: "laborder.png")!, UIImage(named: "pharmacyorder.png")!, UIImage(named: "logout.png")!]

然后我尝试使用这个将它加载到我的收藏视图中

我在集合视图中获取名称但不是图像 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataArray.count }

          func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
              let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath)  as! ItemCell
              cell.setData(text: self.dataArray[indexPath.row])
              cell.setData(UIImageView: self.dataArray[indexPath.row])


              return cell
          }

当我使用它时,这条线给出了错误:调用中的参数标签不正确(有'UIImageView:',预期的'文本:')

          cell.setData(UIImageView: self.dataArray[indexPath.row])

我的 ItemCell 类

class ItemCell: UICollectionViewCell {

    @IBOutlet weak var textLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        self.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1).cgColor
        self.layer.shadowOffset = CGSize(width: 0.0, height: 3.0)
        self.layer.shadowOpacity = 1.0
        self.layer.shadowRadius = 10.0
        self.layer.masksToBounds = false
        self.contentView.layer.cornerRadius = 16.0
            }

    func setData(text: String) {
        self.textLabel.text = text



    }


}

标签: iosswiftswift5

解决方案


setData(UIImageView:这里的错误清楚地表明你的类中没有方法ItemCellItemCell向接受类型的类添加一个UIImage并实现将图像设置为 imageView 的方法,你就可以开始了。在此之前,请确保单元格已UIImageView添加并且已连接到for@IBOutlet中的。这是一个例子:ItemCellimageView

class ItemCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!

    func setData(image: UIImage) {
        imageView.image = image
    }
}

注意:您也应该在一定程度上修改您的命名约定。


推荐阅读