是否有一种魔术方法接受两个视图并返回它们彼此之间的距离(可能是x和y距离)?或者这是必须手动完成的事情吗?
答案 0 :(得分:4)
要获得你正在寻找的神奇方法,你应该在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 docs。
答案 1 :(得分:2)
手动。只要没有应用于视图的变换,编写一些计算2视图框架矩形之间距离的代码就不难了。
在这里大声思考:
如果无法在2个视图框架矩形之间的空间中绘制垂直和水平线,则距离将是最近边之间的x距离或y距离。
如果您可以在视图之间绘制水平线和垂直线(它们在x维度或y维度上不重叠),则两个视图之间的距离将是其最近角落之间的毕达哥拉斯距离
答案 2 :(得分:1)
必须手动完成。
- (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()可以帮到你很多。