2017-10-11 2 views
2

Je suis un débutant dans le développement iOS, et je suis un tutoriel pour mettre en œuvre la vue de collection.UICollectionView l'espacement des éléments ne peut pas être ajusté

Voici la capture d'écran de cette application:

as we can see, the space between cell and line is quite big

Je veux faire cet écart entre les éléments le plus près possible. J'ai essayé de mettre en œuvre le code ci-dessous:

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) 

J'ai également changé l'espacement minimal pour la cellule et la ligne à 0,1 en story-board principale comme ceci:

minimimum spacing in storyboard

mais l'écart est encore grand . qu'est-ce qui a mal tourné ici?

+0

peut que cela vous aide. https://stackoverflow.com/questions/35654129/how-to-change-space-between-cells-in-uicollectionview/35654505#35654505 –

+0

L'imageView se remplit-elle sur chaque cellule? Vous pouvez utiliser la vue de débogage hiérarchie pour le vérifier – jojoT

Répondre

3

Vous pouvez gérer par l'utilisation de la méthode UICollectionViewDelegateFlowLayout

Pour EX.

utilisation ci-dessous pour la méthode gérer

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. 
} 
0

Vous devez calculer correctement la taille de l'élément, car même 1 pixel peut provoquer la mise en page perturbée. Peu de changement pour répondre @iPatel

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 

}

espoir cette aide