beasone beasone - 4 months ago 19
iOS Question

The size of UICollectionViewCell will be different when I scroll the screen

I create a

UICollectionViewController
and I want it to show three cells in each row. Each cell's width should be 1/3 of the whole screen. However, when I first enter the
UICollectionViewController
scene, all the cells are very small. When I scroll the screen, some cells become larger cells which have the expected size. enter image description here
enter image description here
enter image description here

Part of my code:

class imageCollectionViewController: UICollectionViewController {
private let reuseIdentifier = "photoCell"
var photos:albumCellModel?
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.toolbarHidden = true

if let layout = collectionView!.collectionViewLayout as? UICollectionViewFlowLayout {
let itemWidth = view.bounds.width / 3.0
let itemHeight = layout.itemSize.height
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
layout.invalidateLayout()
}
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let photos = photos
{
return photos.photoSet.count
}
return 0
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("photoCell", forIndexPath: indexPath) as! imageCollectionViewCell
cell.imageView.image = photos?.photoSet[indexPath.row].image
return cell
}

Answer

I do encounter the same problem with my previous project. I managed to solve the problem by using this library. Snapkit.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! TestCell
let width = self.view.bounds.size.width/2 - 10
    cell.imageView.snp_makeConstraints { (make) -> Void in
        make.width.equalTo(width)
        make.height.equalTo(3*width/2)
    }

return cell

}

Just put only top and leading constraint on the imageView in the storyboard. Hope it helps.

Comments