Reputation: 25934
I am making a menu, where I know the cells upfront. Therefore I create each cell UICollectionViewCell()
in code. That use to work in UITableView
, but in UICollectionView
it gives error in cellForItemAt
:
does not have a reuseIdentifier - cells must be retrieved by calling -
dequeueReusableCellWithReuseIdentifier:forIndexPath:
'
Ok, so when I create each UICollectionViewCell
(Custom super cell). It wants cell identifier, no problem. But I also wants IndexPath
.
So the question is; how can I create UICollectionViewCell
upfront?
Hope you can understand.
Upvotes: 0
Views: 1513
Reputation: 570
Collection view requires that you always dequeue views, rather than create them explicitly in your code. There are two methods for dequeueing views.
Use the
dequeueReusableCell(withReuseIdentifier:for:)
to get a cell for an item in the collection view.Use the
dequeueReusableSupplementaryView(ofKind:withReuseIdentifier:for:)
method to get a supplementary view requested by the layout object.Before you call either of these methods, you must tell the collection view how to create the corresponding view if one does not already exist. For this, you must register either a class or a nib file with the collection view. For example, when registering cells, you use the
register(_:forCellWithReuseIdentifier:)
orregister(_:forCellWithReuseIdentifier:)
method. As part of the registration process, you specify the reuse identifier that identifies the purpose of the view. This is the same string you use when dequeueing the view later.
In delegate method cellForItem(at:)
you need to dequeue cell by passing your reuse identifer and indexpath to method dequeueReusableCell(withReuseIdentifier:for:)
, the returned object will be your cell.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// reference to your cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
return cell
}
If you are using stroyboards you need to set reuse identifier here
and pass it to dequeueReusableCell(withReuseIdentifier:for:)
method
Here you can find more information how to use collection views.
Upvotes: 1