[英]How to fetch the width and height of a programatically added view in Swift/ iOS?
[英]How to give width and height programatically for collection view cell in ios, swift 3
我试图以编程方式给出collectionViewCell
的高度和宽度。 我使用以下方法:
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)
}
这没用。 即使此方法也没有显示出来。 帮帮我 在Swift 3中还有其他委托方法可以通过编程方式设置单元格的宽度和高度吗?
方法collectionView(_:layout:sizeForItemAt:)
是UICollectionViewDelegateFlowLayout
协议的方法,因此仅设置collectionView
delegate
和datasource
是不够的,您需要使用自定义类实现UICollectionViewDelegateFlowLayout
,在该自定义类中,您已经添加collectionView
来调用UICollectionViewDelegateFlowLayout
协议的方法。 因此,实现UICollectionViewDelegateFlowLayout
如下例所示:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
请确保您的类必须实现UICollectionViewDelegateFlowLayout,如下所示:
class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
{
...
}
然后在您的类中编写此委托方法:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: 100, height: 100) // The size of one cell
}
希望对您有帮助...
此方法始终有效。 请首先确保不执行此方法。 如果不是,则编写委托UICollectionViewDelegateFlowLayout
如下所示:
class MyViewController: UIViewController , UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource{
:
:
}
而且不要忘了从情节提要或通过代码collectionView.delegate = self
和collectionView.datasource = self
绑定UICollectionView的委托和数据源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.