简体   繁体   English

集合视图单元格不会改变大小

[英]Collection View Cell Will Not Change Size

I am trying to create an application with a collection view.我正在尝试创建一个带有集合视图的应用程序。 No matter what I do, I cannot change its size.无论我做什么,我都无法改变它的大小。 In the view controller, it looks larger than when program is ran (photos below).在视图 controller 中,它看起来程序运行时大(下图)。 The image view is the same size as the cell.图像视图与单元格大小相同。 I have also tried using我也尝试过使用

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

But nothing changes.但没有任何改变。

Here is the viewcontroller code:这是视图控制器代码:

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 is just a UICollectionViewCell class with an outlet to the imageview. myCell 只是一个 UICollectionViewCell class 与 imageview 的插座。

To call the sizeForItemAt method, make sure that your class adopts both UICollectionViewDelegate and UICollectionViewDelegateFlowLayout protocols.要调用 sizeForItemAt 方法,请确保您的 class 采用UICollectionViewDelegateUICollectionViewDelegateFlowLayout协议。

You have to use this function in your viewController你必须在你的 viewController 中使用这个 function

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

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

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