Cell spacing in UICollectionView

后端 未结 26 3600
旧巷少年郎
旧巷少年郎 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:36

    I'm using monotouch, so the names and code will be a bit different, but you can do this by making sure that the width of the collectionview equals (x * cell width) + (x-1) * MinimumSpacing with x = amount of cells per row.

    Just do following steps based on your MinimumInteritemSpacing and the Width of the Cell

    1) We calculate amount of items per row based on cell size + current insets + minimum spacing

    float currentTotalWidth = CollectionView.Frame.Width - Layout.SectionInset.Left - Layout.SectionInset.Right (Layout = flowlayout)
    int amountOfCellsPerRow = (currentTotalWidth + MinimumSpacing) / (cell width + MinimumSpacing)
    

    2) Now you have all info to calculate the expected width for the collection view

    float totalWidth =(amountOfCellsPerRow * cell width) + (amountOfCellsPerRow-1) * MinimumSpacing
    

    3) So the difference between the current width and the expected width is

    float difference = currentTotalWidth - totalWidth;
    

    4) Now adjust the insets (in this example we add it to the right, so the left position of the collectionview stays the same

    Layout.SectionInset.Right = Layout.SectionInset.Right + difference;
    

提交回复
热议问题