Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView oval shaped custom cell

How to generate oval shaped cells in UICollectionView using custom cell. Below is the image that I am trying to achieve.

enter image description here

Have no idea about this how to achieve this, gone through several links but doesn't got. Please guide. Thanks

Update: What i tried is

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {


    return CGSize(width: collectionView.frame.size.width/3.0 - 8, height: collectionView.frame.size.width/2.5[![enter image description here][2]][2] )
}

For this design but it's not working as required, it becomes enter image description here

like image 878
iPhone 7 Avatar asked Aug 26 '16 07:08

iPhone 7


1 Answers

TL;DR: (Example can be found here: https://github.com/JakubMazur/SO39160339)


Phew, you will hit 3 problems with this view:

  1. Self sizing UICollectionView cells that take a text as a cell lenght
  2. Align collectionView cells to center not left-right
  3. Rounded corners in subview

So let's start:

1)

This is a little bit tricky and not that much straightforward. The first thing you should do it let auto-layout do the trick for you. So design cell and collectionView in your storyboard and xib file and then in your controller class to this:

if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    flowLayout.estimatedItemSize = CGSizeMake(1, 1)
}

The right way to do is for example viewDidLoad func. Of course if you'll override an layout later remeber about this if.

Then for a label you want to self size you'll need to set:

cell.titleLabel.preferredMaxLayoutWidth = 50

The value you use in that two examples doesn't matter that much. If you set estimatedItemSize low, you basically asking for self sizing.

2)

For doing this you'll need to override the layout class. I highly recommend use this solution https://stackoverflow.com/a/38254368/1317394 from @Alex Koshy answer.

3)

That part is easy.Just add subview on the bottom on custom cell and set cell view background color to transparent. And add corner radius in cell like this:

override func prepareForReuse() {
    self.roundedView.layer.cornerRadius = self.frame.size.height/2

}

Here is an output effect: enter image description here

And here is the link to repository with this example:

https://github.com/JakubMazur/SO39160339

Enjoy!

like image 65
Jakub Avatar answered Oct 16 '22 22:10

Jakub