Benobab
Benobab

Reputation: 428

Custom layout UICollectionView swift

I am trying to achieve a custom layout like this one :

Layout wanted

I am trying to implement it via a UICollectionView. First I use this code to have the desired size :

func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
        return CGSizeMake((collectionView.frame.size.width / 2) - 2 , (collectionView.frame.size.height / 3) - 2)
}

It's working fine.

The problem is that my picture is not properly centered. I did it this way :

Constraints in storyboard

Let me explain :

  1. One constraint to align the center of the uiimage on X

  2. One constraint to do the same thing on Y

  3. One constraint to keep the image ratio

  4. One constrain to say that the height of the image is 70% of the cell height

    And the result is very not the one expected :

Actual result of the Layout

Upvotes: 0

Views: 332

Answers (1)

Kunal
Kunal

Reputation: 227

i did it using custom layout.

    let collLayout:UICollectionViewFlowLayout = layout as! UICollectionViewFlowLayout
    collLayout.scrollDirection = .Vertical
    collLayout.minimumInteritemSpacing = 10
    let width = (frame.size.width - 3*collLayout.minimumInteritemSpacing)*0.5

    collLayout.itemSize = CGSizeMake(width, width)

    collLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10)

And then initialize your collection view with this custom layout.

Upvotes: 2

Related Questions