是否有一种神奇的方法可以接受两个视图并返回它们之间的距离(可能是 x 和 y 距离)?或者这是必须手动完成的事情?
3 回答
要获得您正在寻找的神奇方法,您应该在 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
您可以从如下视图调用此函数:
double distance = [self distanceToView:otherView];
或在两个视图之间,例如:
double distance = [view1 distanceToView:view2];
您还可以编写到最近边缘的距离等类别。上面的公式只是两点之间的距离,我使用了每个视图的中心。有关类别的更多信息,请参阅Apple 文档。
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.
必须手动完成。
- (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() 和 CGRectGetMinY() | CGRectGetMaxY() 可以帮助你很多。