1

Hello I've looked around and haven't been able to find a solution to my question yet. I'm trying horizontally center items of a collectionView where items will have all have different widths and sizes. Because of this, some rows in the section may have 2 items, some may only have 1. Most solutions I've seen around set the UIEdgeInsets but since I don't know whether the row contains how many items, in addition to not knowing the item size, I've been having a hard time getting this to work.

Sample Image

I've attached a picture to show you what I current have. Any suggestions would be greatly appreciated

victorydub
  • 111
  • 10

2 Answers2

0

Choosing correct UI Widget, to achieve what you want in minimum effort. According to your screenshot UITableView should be the right choice for achieving this.

Here are some tips

  1. Use custom UITableViewCell with a label horizontally and vertically centered within the UITableViewCell

  2. Use dynamic sizing, so that if the text grows then the cell grows too.

  3. Remove the separator and background color of the cell, cell's contentView.

Happy coding

Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44
  • 1
    A TableView doesn't achieve what I want, since it would show only 1 label per "row" and I want to to show as many labels in a row as allowed by the label width. – victorydub Oct 23 '18 at 16:50
0

You can use the open source project TagCellLayout written by riteshhgupta in GitHub.

Sample Code to initialize the layout:

import TagCellLayout

let tagCellLayout = TagCellLayout(alignment: .center, delegate: self)
collectionView.collectionViewLayout = tagCellLayout

enter image description here

I know you might write the lots of code for this, but it would be helpful greatly and even you can customize to different layout alignments.

Sateesh Yemireddi
  • 4,289
  • 1
  • 20
  • 37