【问题标题】:Collection View Cell Will Not Change Size集合视图单元格不会改变大小
【发布时间】:2019-11-18 04:27:09
【问题描述】:

我正在尝试创建一个带有集合视图的应用程序。无论我做什么,我都无法改变它的大小。在视图控制器中,它看起来 larger 比程序为 ran 时(下图)。图像视图与单元格大小相同。我也尝试过使用

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
         return CGSize(width: screenWidth/3, height: screenWidth/3)
    }

但没有任何改变。

这是视图控制器代码:

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    let array = ["1,", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return array.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCell
        cell.myImageView.image = UIImage(named: array[indexPath.row] + ".jpg")

        return cell
    }

}

myCell 只是一个 UICollectionViewCell 类,带有一个到 imageview 的出口。

【问题讨论】:

    标签: ios swift xcode uicollectionview


    【解决方案1】:

    要调用 sizeForItemAt 方法,请确保您的类同时采用 UICollectionViewDelegateUICollectionViewDelegateFlowLayout 协议。

    【讨论】:

      【解决方案2】:

      你必须在你的 viewController 中使用这个函数

      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {        
              return CGSize(width: UIScreen.main.bounds.height, height: <Desired Height>)
          }
      }
      

      【讨论】: