سؤال

Is there a magic method that accepts two views and returns how close they are to one another (perhaps the x and y distances)? Or is this something that must be done manually?

هل كانت مفيدة؟

المحلول 2

Manually. As long as there is no transform applied to the views, it shouldn't be that hard to write some code that would calculate the distance between the 2 view's frame rectangles.

Thinking out loud here:

If you can't draw a vertical and horizontal line in the space between the 2 views frame rectangles, the distance will be the x distance or y distance between the nearest sides.

If you can draw both a horizontal line and a vertical line between the views (they don't overlap in either the x dimension or the y dimension) then the distance between the 2 views will be the pythagorean distance between their nearest corners.

نصائح أخرى

To get the magical method you're looking for you should write a category on UIView:

// UIView+distance.h
#import <UIKit/UIKit.h>

@interface UIView (distance)
-(double)distanceToView:(UIView *)view;
@end


// UIView+distance.m
#import "UIView+distance.h"

@implementation UIView (distance)
-(double)distanceToView:(UIView *)view
{
    return sqrt(pow(view.center.x - self.center.x, 2) + pow(view.center.y - self.center.y, 2));
}
@end

You can call this function from a view like:

double distance = [self distanceToView:otherView];

Or between two views like:

double distance = [view1 distanceToView:view2];

You could also write categories for distance to closest edge, etc. The above formula is just the distance between two points, I used the center of each view. For more information on categories see the Apple docs.

Must be done manually.

- (double)distance:(UIView*)view1 view2:(UIView*)view2
{
       double dx = CGRectGetMinX(view2) - CGRectGetMinX(view1);
       double dy = CGRectGetMinY(view2) - CGRectGetMinY(view1);

       return sqrt(dx * dx + dy * dy);
       or
       return sqrt(pow(dx, 2) + pow(dy, 2));
}

CGRectGetMinX() | CGRectGetMaxX() and CGRectGetMinY() | CGRectGetMaxY() can help you a lot.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top