如何以编程方式在UICollectionView中为不同文本的不同单元格添加不同的图像?

时间:2017-04-07 06:09:41

标签: ios swift swift3

我想以编程方式为textLabel中的不同UIcollectionView的不同单元格添加不同的图像。我尝试了很多方法,但它只显示错误。

这是我的代码:

import Foundation
import UIKit

class HomeCVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    let homeCellId = "homeId"

    override func viewDidLoad() {
        super.viewDidLoad()

        //  homeObjects = HomeObject.sampleObjectHeadline()

        navigationItem.title = "Home"
        collectionView?.backgroundColor = .green

        collectionView?.register(HomeCell.self, forCellWithReuseIdentifier: homeCellId)
    }

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

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

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 150)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

}


class HomeCell: UICollectionViewCell {

    override init(frame: CGRect){
        super.init(frame: frame)

        homeImageViewSetup()
    }

    let homeImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.backgroundColor = .blue
        imageView.image = UIImage(named: "imageName")
        // imageView.contentMode = .scaleAspectFill
        // imageView.clipsToBounds = true
        imageView.layer.cornerRadius = 5
        imageView.layer.masksToBounds = true
        imageView.translatesAutoresizingMaskIntoConstraints = false

        return imageView
    }()

    let homeImageLabel: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 20, y: -10, width: 200, height: 80)
        label.textColor = .white
        label.text = "Welcome to my Page"
        return label
    }()

    func homeImageViewSetup() {
        addSubview(homeImageView)
        addSubview(homeImageLabel)
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-5-[v0]-5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": homeImageView]))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-5-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": homeImageView]))

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

2 个答案:

答案 0 :(得分:1)

您可以在此方法中配置homeImageLabel.texthomeImageView.imagecollectionView(_:cellForItemAt:)。例如:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: homeCellId, for: indexPath) as! HomeCell
    cell.homeImageView.image = UIImage(named: "imageName")
    cell.homeImageLabel.text = "Welcome to my Page"
    return cell
}

您应该创建一个数组来存储图像和文本,并使用indexPath检索每个项目。

struct Item {
    var imageName: String
    var text: String
}

let data: [Item] = [
    Item(imageName: "imageName", text: "Welcome to my Page"),
    Item(imageName: "otherImageName", text: "Other text"),
]

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

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

    let item = data[indexPath.item]
    cell.homeImageView.image = UIImage(named: item.imageName)
    cell.homeImageLabel.text = item.text

    return cell
}

答案 1 :(得分:0)

您必须使用Array Of Dictionary,字典包含单个单元格的特定数据。

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

    func collectionView(_collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("caseImage", forIndexPath: indexPath)

        let dictInfo = arrCaseImage[indexPath.row]
        let imgName = dictInfo["image"]
        let txtLbl  = dictInfo["text"]

        let urlStr = "http://case/\(imgName)"   
        let imgView = cell.viewWithTag(101) as! UIImageView
        imgView.af_setImageWithURL(NSURL(string: urlStr)!, placeholderImage: UIImage())
        //set label txt here
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 150)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }