【问题标题】:How to give width and height programatically for collection view cell in ios, swift 3如何以编程方式为ios中的集合视图单元格提供宽度和高度,swift 3
【发布时间】:2016-12-16 10:56:31
【问题描述】:

我试图以编程方式给出 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 中是否有任何其他委托方法可以通过编程方式设置单元格的宽度和高度?

【问题讨论】:

    标签: ios uicollectionview swift3 uicollectionviewcell


    【解决方案1】:

    方法collectionView(_:layout:sizeForItemAt:)UICollectionViewDelegateFlowLayout协议的方法,所以设置collectionViewdelegatedatasource是不够的,你需要用你添加collectionView的自定义类来实现UICollectionViewDelegateFlowLayout调用UICollectionViewDelegateFlowLayout 协议的方法。所以像下面的例子一样实现UICollectionViewDelegateFlowLayout

    class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    【讨论】:

      【解决方案2】:

      请确保您的班级必须像这样实现 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
      }
      

      希望对你有帮助...

      【讨论】:

        【解决方案3】:

        这种方法总是有效的。请首先确保没有执行此方法。如果没有,写委托UICollectionViewDelegateFlowLayout 如下:

        class MyViewController: UIViewController , UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource{
           :
           :
        }
        

        别忘了从故事板或代码collectionView.delegate = selfcollectionView.datasource = self绑定UICollectionView的委托和数据源

        【讨论】:

          猜你喜欢
          • 2021-10-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-22
          • 1970-01-01
          相关资源
          最近更新 更多