UICollectionView vertically centered

I have an object of size UICollectionView size (320 500).

I need to create a UICollectionView so that the content is vertically centered. So, if the total size of the content is (100 100), then the cells should be drawn in the rectangle (0,200): (320 300). i.e. 50 above and 50 below the vertical center by 250.

Problem. The number of cells and the size of cells is determined only at runtime. For example, if the text with a cell can be 1 line, the size is ~ (100.50). If the size of 4 lines is ~ (100,200). So only after I launched collectionView:sizeForItemAtIndexPath: for the last cell, I can determine what the starting position for the first cell should be.

Any initial suggestion on how I should approach this issue. Even if I'm a subclass of Flowlayout , how do I know the position of the first cell before I draw the last?

+1
ios uicollectionview uicollectionviewlayout
source share
2 answers

As I did, this is selecting the layout attributes of the last item as a collection, and then selecting the content to represent. The problem is that changing the insert is not smooth, since there is no animation, but on the other hand it works.

 -(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect { NSArray* array = [super layoutAttributesForElementsInRect:rect]; UICollectionViewLayoutAttributes* att = [array lastObject]; if (att){ CGFloat lastY = att.frame.origin.y + att.frame.size.height; CGFloat diff = self.collectionView.frame.size.height - lastY; if (diff > 0){ UIEdgeInsets contentInsets = UIEdgeInsetsMake(diff/2, 0.0, 0.0, 0.0); self.collectionView.contentInset = contentInsets; } } return array; } 
+1
source share

You can use the delegate method insetForSectionAtIndex to center the cells:

 #pragma mark collection view cell paddings - (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { float leftInset = (self.view.frame.size.width - (COUNT_OF_CELL*WIDTH_OF_CELL + COUNT_OF_CELL-1 * SPACE_BETWEEN_CELLS)) / 2; return UIEdgeInsetsMake(0, leftInset, 0, 0); // top, left, bottom, right } - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { return 8; // this is SPACE_BETWEEN_CELLS } 

You must change COUNT_OF_CELL (this is the account of your array), WIDTH_OF_CELL, SPACE_BETWEEN_CELLS, and it will work as you wish.

+1
source share

All Articles