UICollectionView
アプリに&を使用するタグ バーがあり、UICollectionViewFlowLayout
1 行のセルが中央揃えになっています。
正しいインデントを取得するには、すべてのセルの合計幅 (間隔を含む) を の幅から引き、UICollectionView
2 で割ります。
[........Collection View.........]
[..Cell..][..Cell..]
[____indent___] / 2
=
[_____][..Cell..][..Cell..][_____]
問題はこの機能です -
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
前に呼び出されます...
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
...そのため、セルを反復処理して合計幅を決定することはできません。
代わりに、各セルの幅を再度計算する必要があります。私の場合[NSString sizeWithFont: ... ]
、セルの幅は UILabel 自体によって決定されるため、使用します。
- (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);
}