简体   繁体   中英

UICollectionView vertically Centred

I have a UICollectionView object of size (320,500).

I need a to create the UICollectionView in such a way that contents are vertically centred. Means if total size of the content is (100,100) then the cells should drawing itself in a rect (0,200):(320,300). that is 50 above and 50 below the vertical centre at 250.

Problem is The number of cells and size of cells is decided only at runtime. For example if the text with in the cell can be 1 line is of size ~ (100,50) . If it is 4 lines size will be ~ (100,200). So it is only after I have run collectionView:sizeForItemAtIndexPath: for the last cell that I can determine what should be starting position for first cell.

Any starting suggestion how I should approach this problem. Even if I subclass Flowlayout how will I know the position of the first cell before I draw the last one ?

You can use insetForSectionAtIndex delegate method to center 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 the COUNT_OF_CELL (this is count of your array), WIDTH_OF_CELL,SPACE_BETWEEN_CELLS and it will work as you wish

How I did it was by fetching the layout attributes of the last element in collection view and then deciding the contentInsets for the view. The problem it has is that the change in inset is not smooth since there is no animation but other wise 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;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM