Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView cell borders in a flow layout

I'm using UICollectionView to lay out a bunch of cells that are sectioned by first letter of their title. Each cell should have a very thin border around it, and the section headers should have borders above and below. Here's my current prototype:

Grid of large equally-sized cells, four to a row, with slim light gray headings between sections. Narrow gray borders show the edges of the cells and dividers.

I achieve the current appearance with the following rules:

  1. Stroke the right and bottom edge of each cell.
  2. Stroke the bottom edge of each section heading.

This is very close to what I want, but there are two defects:

  1. If the line before a section heading isn't full, then the border along the top of the heading stops short of the right edge of the screen.
  2. It's not visible in this screenshot, but if a line is full, the right border of the last cell in the line is still drawn, which looks a little odd against the edge of the screen.

My best idea to fix this is to somehow tell each cell if it's in the last row of a section or the last cell in a row; then the cell would turn off the offending borders, section headings would draw a top border as well as a bottom, and everything would be hunky-dory. I don't know how to achieve that, though.

Any thoughts on how to manage that, or another way to get the look I'm going for? I'm currently using a UICollectionViewFlowLayout.

like image 441
Becca Royal-Gordon Avatar asked Dec 27 '22 00:12

Becca Royal-Gordon


1 Answers

I ended up subclassing UICollectionViewFlowLayout and applying several heuristics after the flow layout had calculated the attributes for each cell:

  1. If center.y is equal to center.y of the last item in the section, the cell is in the last row of the section.
  2. If CGRectGetMaxY(frame) is equal to CGRectGetMaxY(self.collectionView.bounds), then the cell is agains the right edge of the collection view.

I then stored the results of these calculations in a subclass of UICollectionViewLayoutAttributes, and wrote a UICollectionViewCell subclass whose -applyLayoutAttributes: method would adjust the borders its background view draws based on the additional properties.

I've put the whole mess into a fairly enormous gist so you can see exactly what I did. Happy hacking.

like image 91
Becca Royal-Gordon Avatar answered Jan 09 '23 22:01

Becca Royal-Gordon