Justifying UIVIews on the iPhone: Algorithm Help

Posted by coneybeare on Stack Overflow See other posts from Stack Overflow or by coneybeare
Published on 2010-01-24T16:19:18Z Indexed on 2010/06/07 16:32 UTC
Read the original article Hit count: 408

Filed under:
|
|
|

I have been messing around with a way to justify align a collection of UIView subclasses within a containing view. I am having a little bit of trouble with the algorithm and was hoping someone could help spot my errors. Here is pseudocode of where I am now:

// 1 see how many items there are
int count = [items count];

// 2 figure out how much white space is left in the containing view
float whitespace = [containingView width] - [items totalWidth];

// 3 Figure out the extra left margin to be applied to items[1] through items[count-1]
float margin = whitespace/(count-1);

// 4 Figure out the size of every subcontainer if it was evenly split
float subcontainerWidth = [containingView width]/count;

// 5 Apply the margin, starting at the second item
for (int i = 1; i < [items count]; i++) {
    UIView *item = [items objectAtIndex:i];
    [item setLeftMargin:(margin + i*subcontainerWidth)];
}

The items do not appear to be evenly spaced here. Not even close. Where am I going wrong?

Here is a shot of this algorithm in action: alt text

EDIT: The code above is pseudocode. I added the actual code here but it might not make sense if you are not familiar with the three20 project.

@implementation TTTabStrip (JustifiedBarCategory)
- (CGSize)layoutTabs {
    CGSize size = [super layoutTabs];

    CGPoint contentOffset = _scrollView.contentOffset;
    _scrollView.frame = self.bounds;
    _scrollView.contentSize = CGSizeMake(size.width + kTabMargin, self.height);

    CGFloat contentWidth = size.width + kTabMargin;
    if (contentWidth < _scrollView.size.width) {
        // do the justify logic

        // see how many items there are
        int count = [_tabViews count];

        // 2 figure out how much white space is left
        float whitespace = _scrollView.size.width - contentWidth;

        // 3 increase the margin on those items somehow to reflect.  it should be (whitespace) / count-1
        float margin = whitespace/(count-1);

        // 4 figure out starting point
        float itemWidth = (_scrollView.size.width-kTabMargin)/count;
        // apply the margin
        for (int i = 1; i < [_tabViews count]; i++) {
            TTTab *tab = [_tabViews objectAtIndex:i];
            [tab setLeft:(margin + i*itemWidth)];
        }

    } else {
        // do the normal, scrollbar logic
        _scrollView.contentOffset = contentOffset;
    }
    return size;
}
@end

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c