mercredi 24 juin 2015

Adding constraints to reusable UITableViewCell in Swift

I'm working on an app which displays sports results for different sports. The ranking table should have a dynamic width for its content, based on its length. Currently it's all fixed width, but once one of the columns has a lot of text, it gets cropped at the end:

+-----------------------------+
|          Goals    Diff   Sc |
+--------+-------+-------+----+
| Team 1 |   152 | 15... | 53 | // Should be 152:xxx
+--------+-------+-------+----+
| Team 2 |   146 | 14... | 53 | // Should be 145:xxx
+--------+-------+-------+----+
| Team 3 |    41 | 41... | 53 | // Should be 41:xxx
+--------+-------+-------+----+

Instead, it should analyze the maximum cell width for each individual column and adjust its width based on that. In case the cells become too wide, they should move left, cropping the team's name instead (in fact, it will word wrap if too small).

+-----------------------------+
|          Goa      Diff   Sc |
+--------+-----+---------+----+
| Team 1 | 152 | 152:xxx | 53 |
+--------+-----+---------+----+
| Team 2 | 146 | 145:xxx | 53 |
+--------+-----+---------+----+
| Team 3 |  41 |  41:xxx | 53 |
+--------+-----+---------+----+

I yet have to decide what exactly to do with the cell headers, but that's another problem.

I have already tried computing the cell widths, comparing them to one another and then creating an array of the maximum width per column, which works as it should. However, it requires quite a lot of computing, as it manually creates labels for each column in every row, calls sizeToFit() on it and then comparing its width against the maximum width so far. I can't believe this is the only way to do it.

Then I use this array of widths on each tableView(:cellForRowAtIndexPath:) to add constraints to the dequeued reusable table view cells (and one of the three/how ever many it is labels). Again, having to create 3 constraints in each call of the method doesn't seem optimal to me.

Is there any easier way? Is there already a inbuilt function I'm missing (or perhaps a library for just that)?

See more ..

Aucun commentaire:

Enregistrer un commentaire