简体   繁体   中英

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). 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.

To call the sizeForItemAt method, make sure that your class adopts both UICollectionViewDelegate and UICollectionViewDelegateFlowLayout protocols.

You have to use this function in your viewController

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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