appFormation appFormation - 1 year ago 50
iOS Question

What is the best/easiest way to create 'flow layout' type layout in iOS

Q1. I have three controls:

, and
in a single line. I want to programmatically arranged them one after another in a line, without any gaps (similar to Java/Android "Flowlayout" layout), because length of text on each control will change due to the user actions. What is the best/easiest way to achieve "Flowlayout" layout programmatically?

Q2. Related to above, I want each control to resize automatically when the text change due to user actions, so the full text remains visible.

Thanks in advance.

//Edited 11/12/2011

Here is how I plan to achieve horizontal "flow layout" of controls that are contained in viewArray:

-(void) doHorizontalFlowLayout:(NSArray *) viewArray
if(viewArray == nil || viewArray.count <=1
return; //get out of here, no need to continue

UIView *v0= (UIView *) [viewArray objectAtIndex:0]; // first view
CGRect frame0 = v0.frame;

CGFloat sumWidth= 0;
for(int i=1; i < viewArray.count; i++)
UIView *thisView= (UIView*) [viewArray objectAtIndex:i];
sumWidth = sumWidth+ v0.frame.size.width;
CGRect nextFrame= CGRectMake(frame0.origin.x
+sumWidth, thisView.frame.origin.y,
thisView.frame.size.width, thisView.frame.size.height);
thisView.frame= nextFrame;
//the above works for 2 views only. For more than 2 views - reset v0 to point to the ith view
v0 = (UIView*) [viewArray objectAtIndex:i];


Answer Source

Was just struggling with this -- here is my solution:

There's no "flow layout" concept in iOS, so you have to calculate the widths of each control manually and place them absolutely in the parent container. UILabels are a bit different than buttons, as the only way to determine the content size is with the [NSString sizeWithFont:...] method. See here for an example.

In your case, you'll have to listen for when user interaction is complete on whichever element is changing, and use the [UIView setNeedsDisplay] ( method to redrawn the view and subviews.

This is much more difficult than it needs to be, IMHO.