Cell spacing in UICollectionView

后端 未结 26 3601
旧巷少年郎
旧巷少年郎 2020-11-22 15:53

How do I set cell spacing in a section of UICollectionView? I know there is a property minimumInteritemSpacing I have set it to 5.0 still the spaci

26条回答
  •  情深已故
    2020-11-22 16:34

    I stumbled upon a similar problem as OP. Unfortunately the accepted answer did not work for me since the content of the collectionView would not be centered properly. Therefore I came up with a different solution which only requires that all items in the collectionView are of the same width, which seems to be the case in the question:

    #define cellSize 90
    
    - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
        float width = collectionView.frame.size.width;
        float spacing = [self collectionView:collectionView layout:collectionViewLayout minimumInteritemSpacingForSectionAtIndex:section];
        int numberOfCells = (width + spacing) / (cellSize + spacing);
        int inset = (width + spacing - numberOfCells * (cellSize + spacing) ) / 2;
    
        return UIEdgeInsetsMake(0, inset, 0, inset);
    }
    

    That code will ensure that the value returned by ...minimumInteritemSpacing... will be the exact spacing between every collectionViewCell and furthermore guarantee that the cells all together will be centered in the collectionView

提交回复
热议问题