I tried to give the height and width for collectionViewCell
, programatically. I used following method:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let viewWidth = self.deviceWidth/3 - 5
let viewHeight = viewWidth
return CGSize(width :100,height: 100)
}
This didn't work. even this method didn't show as a hint. Help me with this. Is there any other delegate method to set the cell width and height programmatically in Swift 3?
Method collectionView(_:layout:sizeForItemAt:)
is UICollectionViewDelegateFlowLayout
protocol's method, so setting delegate
and datasource
of collectionView
is not enough, you need to implement UICollectionViewDelegateFlowLayout
with your custom class where you have added collectionView
to call UICollectionViewDelegateFlowLayout
protocol's methods. So implement UICollectionViewDelegateFlowLayout
like below example:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
Pls sure your class must implement UICollectionViewDelegateFlowLayout like this:
class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
{
...
}
And then write this delegate method in your class:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: 100, height: 100) // The size of one cell
}
Hope it will help you...
This methods always work. Please first ensure that this method is executed ot not. If not, the write delegate UICollectionViewDelegateFlowLayout
like this:
class MyViewController: UIViewController , UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource{
:
:
}
And dont forget to bind the delegate and datasource of UICollectionView either from storyboard or by code collectionView.delegate = self
and collectionView.datasource = self