Abhi Abhi - 4 months ago 28
Swift Question

UIImageView appearing very small in UICollectionViewCell though image is large

Using auto layout, I have created

UICollectionView
and added an
UIImageView
inside it to show various category images. But when I run the app, though the cell is taking appropriate area on screen but
UIImageView
contained inside it is appearing very small. Any suggestion how to fix this? I am using Swift.

Using auto-layout's Pin option, I have pinned
UIImageView
to all edges of
UICollectionViewCell
.

In Xcode storyboard it looks like this:
Cell Size is 150 x 150

After running app, it is looking like this:
App view in simulator

I want
UIImageView
to cover all green space of cell to show image. I am using following code to populate
UICollectionView


@IBOutlet weak var categoryCollectionView: UICollectionView!

let categoryImages = [UIImage(named: "cake"), UIImage(named: "flowers"), UIImage(named: "chocolate"), UIImage(named: "greetings"), UIImage(named: "combobox"), UIImage(named: "handicraft"), UIImage(named: "mug"), UIImage(named: "soft_toy")]

let categoryNames = ["Cakes", "Flowers", "Chocolates", "Greetings", "Combos", "Handicraft", "Mugs", "Soft Toys"]


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.categoryNames.count;
}

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

let cell = categoryCollectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! HomeCategoriesCollectionViewCell


cell.categoryImageView?.image = self.categoryImages[indexPath.row]

cell.categoryNameLabel?.text = self.categoryNames[indexPath.row]

return cell
}

Answer

Looks like the contentView is not filling the cell width/height your code is returning. You could try setting the contentView frame to match the bounds of the cell as follows once you have created you cell in cellForItemAtIndexPath:

cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | 
                         UIViewAutoresizing.FlexibleWidth | 
                         UIViewAutoresizing.FlexibleRightMargin |
                         UIViewAutoresizing.FlexibleTopMargin |
                         UIViewAutoresizing.FlexibleHeight | 
                         UIViewAutoresizing.FlexibleBottomMargin

or Swift 2

cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = [.FlexibleLeftMargin,
                          .FlexibleWidth,
                          .FlexibleRightMargin,
                          .FlexibleTopMargin,
                          .FlexibleHeight,
                          .FlexibleBottomMargin]