I have implemented a UICollectionView, the cell size is w90 h90. When i run it on iPhone 6 i get the proper spacing between cell but when i do it on iPhone 5s i get more spacing between cell. My question is how do i change cell size based on the device screen size, suppose if the cell size was w80 h80 i get proper results on iPhone 5s too. what I'm presently doing is
override func viewWillAppear(animated: Bool) {
var scale = UIScreen.mainScreen().scale as CGFloat
println("Scale :\(scale)")
var cellSize = (self.collectionViewLayout as UICollectionViewFlowLayout).itemSize
println("Cell size :\(cellSize)")
imageSize = CGSizeMake(cellSize.width * scale , cellSize.height * scale)
println("Image size : \(imageSize)")
}
// sizeForItemAtIndexPath
func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
return imageSize!
}
Result on iPhone 6 :
Result on iPhone 5s
Objective-C / Swift both fine for solution. Thanks.
Step 1: Implement UICollectionViewDelegateFlowLayout(if not done).
Step 2: Use delegate method of UICollectionViewDelegateFlowLayout.
Step 3: Go to XIB or StoryBoard where you have your CollectionView.
Step 4: In XIB or StoryBoard where you have your CollectionView click on CollectionView.
Step 5: Go to InterfaceBuilder, then in second last tab (ie: Size Inspector) set Min Spacing
For Cells = 5
For Lines = 5
That it.
and vice versa.
Swift 3 Version
For a slightly more flexible answer
Allows you to adjust number of columns and spacing, expanding on Zaid Pathan's answer
To expand on Tim's answer, there is a small caveat relating to partial point widths: Rounding of partial point widths might cause the width to be wider than will allow the number of desired columns. One way to work around this is to truncate the width using trunc():
Objective-c
example:use this function