Reputation: 13803
I am a beginner in iOS development, and I am following a tutorial to implement collection view.
Here is the screenshot of that app :
I want to make that gap between items as close as possible. I have tried to implement the code below:
struct StoryBoard {
static let leftAndRightPaddings : CGFloat = 1.0
static let numberOfItemsPerRow : CGFloat = 3.0
}
let collectionViewWidth = collectionView?.frame.width
let itemWidth = (collectionViewWidth! - StoryBoard.leftAndRightPaddings) / StoryBoard.numberOfItemsPerRow
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
I have also changed the minimum spacing for cell and line to 0.1 in main storyboard like this:
but the gap is still big. what went wrong in here?
Upvotes: 2
Views: 194
Reputation: 47049
You can manage by use of UICollectionViewDelegateFlowLayout
method
For EX.
Use below method for manage
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.size.width
var height = 124.0 // Set whatever you want
return CGSize(width: (width / 3) - 0.5, height: CGFloat(height)) // Here (width / 3) means 3 cell display in screen horizontally. you can change here 3 or 2 or 4 etc AND "0.5" is space your can change space between two items that you want.
}
Upvotes: 3
Reputation: 1325
You have to calculate the item size correctly, as even 1 pixel can cause disturbed layout. Little change for @iPatel answer
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let noOfItemsInRow = 3 // the items in single row
let width = UIScreen.main.bounds.size.width
let totalSpace = 8 + 8 + (noOfItemsInRow * 0.5) //8: side margin, 0.5 is the space between 2 items
var height = 124.0 // Set whatever you want
return CGSize(width: ((width - totalSpace) / 3), height: CGFloat(height)) // Here (width / 3) means 3 cell display in screen horizontally. you can change here 3 or 2 or 4 etc
}
hope this help
Upvotes: 0