Search code examples
iosautolayout

How can I use autolayout and wrap multiple UI Labels in a row?


I have a UITableViewCell subclass that displays 7 pieces of information, one label across the top showing the entity name, and then 6 labels with the entity's data. When in portrait, I want the cell to look like:

    | Entity Name                     |
    | [data1]     [data2]     [data3] |
    | [data4]     [data5]     [data6] |

And in landscape I want the cell to look like:

    | Entity Name                                          |
    | [data1]  [data2]  [data3]  [data4]  [data5]  [data6] |

I can accomplish either independently with Autolayout, but is what is the best way to accomplish both? Is there a way to do this with a single set of constraints or should I be removing/adding all the necessary NSLayoutConstraints each time the device is rotated, or is there some other solution?


Solution

  • The approach I would take for this is to use a UICollectionView inside the cell.

    That way the layout of the cell is managed by something that is used to doing this kind of thing and it won't matter how many labels you add if you decide to add some in the future.

    Make the cell a UICollectionViewDelegate / Datasource so that each cell manages its own layout.