Data
Start with what you want in your cells. I will create an array of this class and show it in my CollectionView.class Data {
var colorName: String!
var color: UIColor!
init (colorName: String, color: UIColor) {
self.colorName = colorName
self.color = color
}
}
Cell
You have to be able to access the controls on the cell (besides the view of the cell).class CollectionCell: UICollectionViewCell {
@IBOutlet weak var colorNameLabel: UILabel!
}
View Controller
Tie it all together.class ViewController: UIViewController,
UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var data: [Data] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
data.append(Data(colorName: "light gray", color: UIColor.lightGray))
data.append(Data(colorName: "gray", color: UIColor.gray))
data.append(Data(colorName: "dark gray", color: UIColor.darkGray))
data.append(Data(colorName: "black", color: UIColor.black))
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell
cell.backgroundColor = data[indexPath.row].color
cell.colorNameLabel.text = data[indexPath.row].colorName
return cell
}
}
(Swift 3)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.