我有一个基本的集合视图,是一个彩色网格。我想做的就是在网格单元格中添加一个文本标签。在我的故事板中,我在单元格的内容视图中拖动了一个标签,我在控制整个集合的视图控制器中为这个标签创建了一个出口。我已经在控制整个集合的视图控制器中为这个标签创建了一个出口。但是不知为何我不能在这个视图控制器中设置单元格的文本。我需要做什么呢?
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)
}
}
created an outlet for this label inside the view controller
如果你想在每个单元格中添加一个文本,你就不能这么做。你要做的是将UICollectionViewCell子类化(例如CustomCollectionViewCell)。将Storyboard中的collectionViewCell设置为这个Class,并连接标签。现在你可以设置这样的文本。
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
}