Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to arrange labels in a flowlayout manner?

How do I arrange some UILabels and/or UIButtons of a variable length? I just want to add them to a UITableViewCell and they should arrange in a left-to-right flow, much like lines of text in a paragraph.

I only found possibilities to create lables with a fixed size and position using "initWithFrame:...". Same seems to be true for Interface Builder, as far as I can tell. Any solution is appreciated no matter if it's done in code or using a custom cell XIB-file.

like image 476
Tim Büthe Avatar asked Jun 01 '10 16:06

Tim Büthe


2 Answers

UITableViewCell, UILabel, and UIButton are all subclasses of UIView and the documentation for UIView says:

Layout and subview management

  • A view may contain zero or more subviews.
  • Each view defines its own default resizing behavior in relation to its parent view.
  • A view can manually change the size and position of its subviews as needed.

So, it is certainly possible to do.

You can create your labels and buttons using initWithFrame: with the argument CGRectZero and then resize them (based on the text or whatever) using setBounds: or setFrame: (because right now you're just going to set the size of the view). Then, add these views as subviews of the cell's contentView.

Then, in a custom subclass of UITableViewCell you can implement your solution by overriding the default behavior (which does nothing) of layoutSubviews: to set the origin field of the subview's frames (i.e., CGRect) that will position the subviews in the cell's content view (the size has already been set). You may need to call setNeedsLayout: or layoutIfNeeded:.

This is really a rough outline of how it is possible to implement a solution because there are a lot of details left out. For example, if you resize a button based on the the text of the titleLabel you'll probably want to pad some to the width and height otherwise the button will be the size of the label and will look odd. In the layoutSubviews: method there could be a fair amount of logic to layout the labels and buttons the way you want (e.g., it would be simpler if all the subviews of a cell where of the same type such as all labels) esp. if the subviews could wrap to a new line.

like image 179
yabada Avatar answered Oct 20 '22 16:10

yabada


For multiline UILabels to get the width and height you should use the NSString method sizeWithFont:constrainedToSize:lineBreakMode: you can then use the sizes you get to lay everything out where it needs to be.

like image 41
jj0b Avatar answered Oct 20 '22 16:10

jj0b