How to center align the cells of a UICollectionView?

前端 未结 18 2467
梦如初夏
梦如初夏 2020-11-28 01:33

I am currently using UICollectionView for the user interface grid, and it works fine. However, I\'d like to be enable horizontal scrolling. The grid supports 8

18条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 02:07

    It's easy to calculate insets dynamically, this code will always center your cells:

    NSInteger const SMEPGiPadViewControllerCellWidth = 332;
    
    ...
    
    - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
    {
    
        NSInteger numberOfCells = self.view.frame.size.width / SMEPGiPadViewControllerCellWidth;
        NSInteger edgeInsets = (self.view.frame.size.width - (numberOfCells * SMEPGiPadViewControllerCellWidth)) / (numberOfCells + 1);
    
        return UIEdgeInsetsMake(0, edgeInsets, 0, edgeInsets);
    }
    
    - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
    {
        [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
        [self.collectionView.collectionViewLayout invalidateLayout];
    }
    

提交回复
热议问题