简体   繁体   English

如何检测UIView视图与另一个UIView的接近程度?

[英]How do I detect how close UIView view is to the other UIView?

Is there a magic method that accepts two views and returns how close they are to one another (perhaps the x and y distances)? 有没有一种魔术方法可以接受两个视图并返回它们之间的距离(也许是x和y距离)有多近? Or is this something that must be done manually? 还是这必须手动完成?

To get the magical method you're looking for you should write a category on UIView: 为了获得您正在寻找的神奇方法,您应该在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 . 有关类别的更多信息,请参阅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. 如果您无法在2个视图框架矩形之间的空间中绘制垂直和水平线,则该距离将是最近的两边之间的x距离或y距离。

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. 如果您可以在视图之间绘制水平线和垂直线(它们在x维度或y维度上都不重叠),则两个视图之间的距离将是它们最近的角之间的勾股距离。

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() | CGRectGetMinX()| CGRectGetMaxX() and CGRectGetMinY() | CGRectGetMaxX()和CGRectGetMinY()| CGRectGetMaxY() can help you a lot. CGRectGetMaxY()可以为您提供很多帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM