I have used AutoLayout
with one of my UICollectionView
I'm facing issue with height and width for imageView. I have added UIImageView
in my UICollectionViewCell
like following with below constraints.
UICollectionViewDataSource
methods.
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var width = Int((collectionView.frame.size.width - 30) / 4)
if width % 2 != 0 {
width += 1
}
return CGSize(width: CGFloat(width), height: CGFloat(width))
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
print("Cell Size - \(cell.bounds)")
print("ImageView Size - \(cell.imageView.frame)")
return cell
}
But when I run this the ImageView
is always coming with 70X70
no matter on which device I will run but UICollectionViewCell
size is increasing and decreasing on different devices.
On iPhone 6 it will looks like below.
I have set backgroundColor
of UIImageView
to white color and red color for UICollectionViewCell
so that it will give batter understanding the console log for Cell and ImageView Size is as below.
Cell Size - (0.0, 0.0, 86.0, 86.0)
ImageView Size - (5.0, 5.0, 70.0, 70.0)
Cell Size - (0.0, 0.0, 86.0, 86.0)
ImageView Size - (5.0, 5.0, 70.0, 70.0)
Please any one help me why the imageView size is not increasing or decreasing according to the UICollectionViewCell
. Any help would be appreciated.
After researching a bit I have came up with the following way to solved this issue of AutoLayout
with UICollectionViewCell
. From Xcode 6 CollectionViewCell
doesn't show the contentView
in interface builder, so in the awakeFromNib
of cell I have set its autoresizingMask
and it works like charm.
class CustomCell: UICollectionViewCell {
@IBOutlet
var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
//Below line solved my problem
self.contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
}
}