Prevent overlap of views

208 Views Asked by At

I have an array of subviews of my container view, added programmatically setting the frame manually.
When the user select a filter I would like to zoom the selected views (matching the filter) increasing their size by 1.1 and maintaining the center but preventing the overlap.
Here's my code so far:

- (void) positionSubviewsWithoutOverlapping: (NSArray *) views {
    for (UIView *v in views){
        CGPoint center = v.center;
        v.frame = CGRectMake(v.frame.origin.x, v.frame.origin.y, v.frame.size.width*1.1, v.frame.size.height*1.1);
        v.center = center;
    }
    while ([self repositionSubviews:views]) {
    }
}

- (BOOL) repositionSubviews: (NSArray *) views{
    BOOL somethingChanged = FALSE;
    for (UIView *v1 in views){
        for (UIView *v2 in views){
            if (v1 != v2){
                if (CGRectIntersectsRect(v1.frame, v2.frame)){
                    somethingChanged = TRUE;
                    [self preventOverlapOfView1:v1 View2:v2];
                }
            }
        }
    }
    return somethingChanged;
}

- (void) preventOverlapOfView1: (UIView *) v1 View2: (UIView *) v2  {
    if (CGRectGetMaxX(v1.frame) > CGRectGetMinX(v2.frame)){
        CGFloat diff = CGRectGetMaxX(v1.frame)-CGRectGetMinX(v2.frame);
        v1.frame = CGRectMake(v1.frame.origin.x-diff, v1.frame.origin.y, v1.frame.size.width, v1.frame.size.height);
    }
    else if (CGRectGetMinX(v1.frame) < CGRectGetMaxX(v2.frame)){
        CGFloat diff = CGRectGetMaxX(v2.frame)-CGRectGetMinX(v1.frame);
        v2.frame = CGRectMake(v2.frame.origin.x-diff, v2.frame.origin.y, v2.frame.size.width, v2.frame.size.height);
    }
    if (CGRectGetMaxY(v1.frame) > CGRectGetMinY(v2.frame)){
        CGFloat diff = CGRectGetMaxY(v1.frame)-CGRectGetMinY(v2.frame);
        v2.frame = CGRectMake(v2.frame.origin.x, v2.frame.origin.y-diff, v2.frame.size.width, v2.frame.size.height);
    }
    else if (CGRectGetMinY(v1.frame) < CGRectGetMaxY(v2.frame)){
        CGFloat diff = CGRectGetMaxY(v2.frame)-CGRectGetMinY(v1.frame);
        v1.frame = CGRectMake(v1.frame.origin.x, v1.frame.origin.y-diff, v1.frame.size.width, v1.frame.size.height);
    }
}

The problem is in - (void) preventOverlapOfView1: (UIView *) v1 View2: (UIView *) v2, I should use CGRectIntersection but I can't figure out how to use it. Does anyone have a suggestion?

1

There are 1 best solutions below

2
On

As a slightly leftfield suggestion, why dont you just use a UICollectionView? Its designed precisely for the type of application you are suggesting. You can zoom in a certain cell and it will automatically move the other cells around to accomodate the change in size.

If not, then I would suggest you use autolayout for this. That again will better help other views not to overlap. But the collection view would be the best option.