I want to display as many collectionViewCells
with buttons
as there are strings in my array. but when I start the simulator there is just the background of the CollectionView
but no cells shown. What could be the error?
Here is the code from my CollectionViewController
that I attached to the CollectionView
in the main.storyboard:
class CollectionViewController: UICollectionViewController {
var Array = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Array = ["1","2","3","4","5"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsSection section: Int) -> Int {
return Array.count
}
override func
collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! UICollectionViewCell
var button = cell.viewWithTag(1) as! UIButton
button.titleLabel?.text = Array[indexPath.row]
return cell
}
}
These are the connections of the Collection View Controller:
The View Controller on the Storyboard:
An object that manages an ordered collection of data items and presents them using customizable layouts.
Open the Storyboard, select the collection view in the attributes inspector change the layout from flow to custom. Below the layout field a new field will appear where you can set the class. Type the name of our subclass. Now open the ViewController.
Did you set the CollectionViewController
to the storyboard identity inspector? :)
And I would try to call the reloadData()
after you change the data in the viewDidLoad
method.
Hope that helps
func layoutCells() {
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 10)
layout.minimumInteritemSpacing = 5.0
layout.minimumLineSpacing = 5.0
layout.itemSize = CGSize(width: (UIScreen.mainScreen().bounds.size.width - 40)/3, height: ((UIScreen.mainScreen().bounds.size.width - 40)/3))
collectionView!.collectionViewLayout = layout
}
Try this. Call this function from view did load. I think the problem is that your collection is not laid out correctly.
func viewDidLoad() {
layoutCells()
}
If this works you can modify the layout options to meet your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With