繁体   English   中英

如何以编程方式为iOS中的集合视图单元格提供宽度和高度,Swift 3

[英]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 delegatedatasource是不够的,您需要使用自定义类实现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 = selfcollectionView.datasource = self绑定UICollectionView的委托和数据源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM