Search code examples
iosautolayoutuikit

iOS: How to display a box of 'tappable tags'


My use-case is like this:

The user defined some tags (text like "#asdf", "#qwerty", "#let_me_think_about_it" and "#decide later"). I want to display these in a box without scrolling (and don't know, how many tags the user created until I display the box).

The box itself should not be scrollable at all but be shown in a UITableViewCell (which is being scrolled). So it must compute the proposed height and respond to Autolayout mechanisms. If a (ARM) Mac user resizes the window to be smaller than before (or an iOS user rotates the device), the box should increase/decrease its height, as necessary (within the limits of Autolayout, since I know of some issues). Each of the tags should be (de)selectable at the same time (UILabel with UITapGestureRegognizer attachted?) and be able to displayed 'selected' (via a background view).

So, the box should primary try to align all content horizontal. If There's not enough horizontal space, do a "line break" and continue on the next "line".

My current solution is a UIScrollView that the user can scroll horizontal and tap any of the (UILabel) views. The displayed views itself are being loaded from a NIB file, like a UITableView does. The issue here is that not any of the selected tags might be visible at the first glance.

If there was no Autolayout, I'd exactly know what to do. But since there it is, I want to use Autolayout in my NIB files and wonder what you would do?

(How do you compute the required width of such a view and decide when a line break is to be done (and how?))

I think I need a simple hint. But if it needs code to explain, ObjC and Swift is both acceptable. :-)


Solution

  • So, the box should primary try to align all content horizontal. If There's not enough horizontal space, do a "line break" and continue on the next "line".

    This sounds like a job for UICollectionView with UICollectionViewFlowLayout. You can disable scrolling, and the layout object will tell you the size of the content so that you can adjust the size of the box.

    (How do you compute the required width of such a view and decide when a line break is to be done (and how?))

    If you're doing it yourself, you add up the widths of all the items on the first line, and if it's larger than the available space, you move the item that extends past the limit and any subsequent items to the next line. Repeat as needed. But that's exactly what a flow layout does for a collection view, so there's no need to roll your own.