[英]How to give width and height programatically for collection view cell in ios, swift 3
I tried to give the height and width for collectionViewCell
, programatically. 我试图以编程方式给出
collectionViewCell
的高度和宽度。 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?
在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. 方法
collectionView(_:layout:sizeForItemAt:)
是UICollectionViewDelegateFlowLayout
协议的方法,因此仅设置collectionView
delegate
和datasource
是不够的,您需要使用自定义类实现UICollectionViewDelegateFlowLayout
,在该自定义类中,您已经添加collectionView
来调用UICollectionViewDelegateFlowLayout
协议的方法。 So implement UICollectionViewDelegateFlowLayout
like below example: 因此,实现
UICollectionViewDelegateFlowLayout
如下例所示:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
Pls sure your class must implement UICollectionViewDelegateFlowLayout like this: 请确保您的类必须实现UICollectionViewDelegateFlowLayout,如下所示:
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: 如果不是,则编写委托
UICollectionViewDelegateFlowLayout
如下所示:
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
而且不要忘了从情节提要或通过代码
collectionView.delegate = self
和collectionView.datasource = self
绑定UICollectionView的委托和数据源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.