How to display 3 cells per row in a UICollectionView?

I used a custom thread layout according to this post . Here is my implementation:

@implementation CustomLayout
-(void)prepareLayout{
[super prepareLayout];
//    [self invalidateLayout];
if(self.collectionView){
    CGSize newItemSize=self.itemSize;

// Number of items per row
    int itemsPerRow=3;

    float totalSpacing=self.minimumLineSpacing*(itemsPerRow-1);

    newItemSize.width=(self.collectionView.bounds.size.width -totalSpacing)/itemsPerRow;

    if(self.itemSize.height>0){
        float itemAspectRatio=self.itemSize.width/self.itemSize.height;
        newItemSize.height=newItemSize.width/itemAspectRatio;
    }

    [self setItemSize:newItemSize];

}


}
@end

This is what I have: Result What have I missed? I came across some other SO posts, but no luck so far.

+4
source share
4 answers

It turned out that I have a piece of code to align the cell on the left side every 2 cells. When I changed the model to 3 cells, it becomes a mess. I apologize for your time!

-3
source
//Make use of UICollectionViewDelegateFlowLayout Protocol

class RVC: UICollectionViewController {
//some code
}

extension RVC: UICollectionViewDelegateFlowLayout{

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
          var collectionViewSize = collectionView.frame.size
          collectionViewSize.width = collectionViewSize.width/3.0 //Display Three elements in a row.
          collectionViewSize.height = collectionViewSize.height/4.0
          return collectionViewSize
    }

For more information, click on the link below.

UICollectionView

+6

Swift 3.0. ,

,

let numberOfCellsPerRow: CGFloat = 3

flowLayout numberOfCellsPerRow

if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
    let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
    let cellWidth = (view.frame.width - max(0, numberOfCellsPerRow - 1)*horizontalSpacing)/numberOfCellsPerRow
    flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
}
+6

. xib.as iPhone 5 5s 320. 3 , 320/3, , . .

-3

Source: https://habr.com/ru/post/1611706/


All Articles