Collection View Layout Problems

Viewed 51

I'm working with CollectionViews and currently have the problem that everytime I implement a UICollectionViewFlowLayout my original layout gets "destroyed". If I dont implement a FlowLayout, my CollectionView is just one row that has the length of all items in it and everything works fine. But the elements in the CollectionView are spaced really far from another. To use a smaller spacing I need to implement the FlowLayout, but as I do that, my CollectionView uses a grid layout AND each element in it shrinks down to like 20x20 pixels.

Where do I tell the FlowLayout to use just one row and how can I lower the spacing between elements in a CollectionView? I saw something like

ItemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Vertical)
    {
        ItemSpacing = 20
    }

but I dont know where to put that code. Can someone help me? :/

Thats what my current FlowLayout looks like:

    public class TestFlowLayout : UICollectionViewFlowLayout
{
    public TestFlowLayout()
    {
    }

    public override bool ShouldInvalidateLayoutForBoundsChange(CGRect newBounds)
    {
        return true;
    }

    public override UICollectionViewLayoutAttributes LayoutAttributesForItem(NSIndexPath indexPath)
    {
        return base.LayoutAttributesForItem(indexPath);
    }

    public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CGRect rect)
    {
        return base.LayoutAttributesForElementsInRect(rect);
    }

    public override void PrepareLayout()
    {
        base.PrepareLayout();
    }

    public override void InvalidateLayout()
    {
        base.InvalidateLayout();
    }
}

I also tried something like this in my ViewDidLoad:

CollectionView.CollectionViewLayout = new TestFlowLayout
        {
            MinimumLineSpacing = 0,
            MinimumInteritemSpacing = 0,
            SectionInset = new UIEdgeInsets(0, 0, 0, 0),
            ScrollDirection = UICollectionViewScrollDirection.Horizontal
        };

but I still get a grid layout instead of a linear one.

I also added

public override nint NumberOfSections(UICollectionView collectionView)
    {
        return 1;
    }

in my UICollectionViewDataSource. But nothing works..

1 Answers

Cause : If UICollectionView has space for more than one Cell in one direction, it's going to let the Cell fill it. For example, we set the sliding direction of UICollectionView to be horizontal. At this point, if the height of the Cell is insufficient, the following situation may occur:

enter image description here

Solution:

Generally speaking, to display a single row (single column), you only need to make the height of the Cell greater than 1/2 of the height of UICollectionView. Then a row is not enough to put down two cells, so the single-row arrangement will naturally appear:

enter image description here

So in your case you just need to set the Frame of UICollectionView .

Related