在UICollectionView中设置文本标签

时间:2020-06-03 07:31:20

标签: swift uicollectionview uicollectionviewcell

我有一个基本的收集视图,该视图是彩色网格。我要做的就是在网格单元格中添加一个文本标签。在情节提要中,我已将标签拖动到单元格的内容视图内。我已经在控制整个集合的视图控制器中为此标签创建了一个出口。但是以某种方式我无法设置此视图控制器内单元格的文本。我该怎么办?

import UIKit
let reuseIdentifier = "CellIdentifer";

class WordsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet var collectionView: UICollectionView!
    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet var cellView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //UICollectionViewDelegateFlowLayout methods
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
    {

        return 4;
    }
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {

        return 1;
    }


    //UICollectionViewDatasource methods
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        return 1
    }

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

        return 100
    }

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

        cell.backgroundColor = self.randomColor()

        return cell
    }


    // custom function to generate a random UIColor
    func randomColor() -> UIColor{
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
}

1 个答案:

答案 0 :(得分:0)

created an outlet for this label inside the view controller如果您想在每个单元格中都有一个文本,则不能这样做。相反,您想要做的是将UICollectionViewCell子类化(例如CustomCollectionViewCell)。将情节提要中的collectionViewCell设置为此类,然后连接标签。现在,您可以像这样设置文本:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as CustomCollectionViewCell

    cell.backgroundColor = self.randomColor()
    cell.myShinyNewTextLabel.text = "myCustomText"
    return cell
}
相关问题