How can I make the cells in collection view auto resize so that minimum of four cells can at least fit in a single row, and if the frame size is that of iPad, then more cells could fit in row. Four cells should be the minimum number of cells in a row, please see the pictures below for further clarification:
I have a collection view which allows me to add images by using the picker view controller, at first the collection view looks like this:
I can further add images to this collection view and after adding several images, it would like:
Right now if there are four images, the fourth one goes to the next row, I want system to autoresize the cells based on the frame size so that minimum four cells are shown in one row. I'm a newbie and quite new to collection view, can someone please help me on this?
you can decide size of collectionview's cell using following method:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
// Return different cells size
let screenBounds = UIScreen.main.bounds
var width = screenBounds.width
let totalLeftRightInsect = 16
let minimumsSpaceBetweenCell = 5
switch (Condition for detecting device ) {
case "iPhone":
let numberOfCell = 4
let totalSpace = CGFloat(( numberOfCell * spaceBetweenCell) + totalLeftRightInsect)
width = (width - totalSpace) / CGFloat(numberOfCell)
return CGSize(width: width, height: width)
case "ipad":
let numberOfCell = 6
let totalSpace = CGFloat(( numberOfCell * spaceBetweenCell) + totalLeftRightInsect)
width = (width - totalSpace) / CGFloat(numberOfCell)
return CGSize(width: width, height: width)
default:
return CGSize(width: 0.0, height: 0.0)
}}
Answer for Swift3, Xcode 8 with horizantal spacing fixed:
The issue with all earlier answer is that cell size is given CGSizeMake(cellWidth, cellWidth) actually takes all screen leaving no room for margin lines due to which collectionView tries to adjust the row/column spacing by taking one element less in each row and unwanted extra spacing.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let linespacing = 5 //spacing you want horizantally and vertically
let numberOfCell: CGFloat = 3 //you need to give a type as CGFloat
let cellWidth = UIScreen.mainScreen().bounds.size.width / numberOfCell
return CGSizeMake(cellWidth - linespacing, cellWidth - linespacing)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.