J'ai une barre d'étiquettes dans mon application qui utilise une fonction UICollectionView
& UICollectionViewFlowLayout
avec une rangée de cellules alignées au centre.
Pour obtenir le retrait correct, vous devez soustraire la largeur totale de toutes les cellules (y compris l'espacement) de la largeur de votre fichier de texte. UICollectionView
et diviser par deux.
[........Collection View.........]
[..Cell..][..Cell..]
[____indent___] / 2
=
[_____][..Cell..][..Cell..][_____]
Le problème est cette fonction -
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
est appelé avant...
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
...donc vous ne pouvez pas itérer sur vos cellules pour déterminer la largeur totale.
Au lieu de cela, vous devez calculer à nouveau la largeur de chaque cellule, dans mon cas j'utilise [NSString sizeWithFont: ... ]
car la largeur de mes cellules est déterminée par l'UILabel lui-même.
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
CGFloat rightEdge = 0;
CGFloat interItemSpacing = [(UICollectionViewFlowLayout*)collectionViewLayout minimumInteritemSpacing];
for(NSString * tag in _tags)
rightEdge += [tag sizeWithFont:[UIFont systemFontOfSize:14]].width+interItemSpacing;
// To center the inter spacing too
rightEdge -= interSpacing/2;
// Calculate the inset
CGFloat inset = collectionView.frame.size.width-rightEdge;
// Only center align if the inset is greater than 0
// That means that the total width of the cells is less than the width of the collection view and need to be aligned to the center.
// Otherwise let them align left with no indent.
if(inset > 0)
return UIEdgeInsetsMake(0, inset/2, 0, 0);
else
return UIEdgeInsetsMake(0, 0, 0, 0);
}