您的位置:首页 > 产品设计 > UI/UE

UIView中的各种坐标转换convertPoint:toView OR convertPoint:fromView

2016-08-15 19:52 357 查看
开发过程中,我们经常会判断A和B之间是否相交或者AB之间是否相互包含,系统封装了

一些方法供我们使用

CGRectContainsRect(<#CGRect rect1#>, <#CGRect rect2#>)
CGRectContainsPoint(<#CGRect rect#>, <#CGPoint point#>)
CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)

1.表示rect1和rect2是否相交

2.表示rect中是否包含point坐标

3.表示rect1中是否包含rect2

那么当坐标不确定的情况下,如何将多层级的View相互转换坐标呢,如下图所示,给大

家简单介绍下方法

- (CGPoint)convertPoint:(CGPoint)point toView:(nullable UIView *)view;
- (CGPoint)convertPoint:(CGPoint)point fromView:(nullable UIView *)view;
// 后面就具体使用下面的代码举例,下面的会了,上面的自然也就会了
- (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;
- (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;




以这个图片为例

FromView

CGRect rec = [self.view convertRect:self.yellowView.frame fromView:self.greyView];
NSLog(@"%@",NSStringFromCGRect(rec));

这句代码的意思是灰色View中的黄色View相对于self.view中的位置


InView

CGRect newRect = [self.yellowView convertRect:CGRectMake(50, 50, 20, 20) toView:self.blueView];

这句代码的意思是在黄色View中,定义一个相对于黄色View(50,50),大小为(20,20)的View,这个View相对于蓝色View的位置


需要注意的是:ToView是可以传nil的

CGRect newRect = [self.yellowView convertRect:CGRectMake(50, 50, 20, 20) toView:nil];

这句代码的意思是在黄色View中,定义一个目标区域,该区域相对于window的位置(nil代表的是self.view.window


下面来展示三个方法如何做到黄色View在Window中的位置

前两种(ToView)

CGRect newRect = [self.yellowView convertRect:self.yellowView.bounds toView:nil];

CGRect newRect = [self.greyView convertRect:self.yellowView.frame toView:nil];
这样也正好表明了frame和bounds的区别,第一段代码表示,在yellowView中,有个

和yellowView一样的大小的区域bounds,此区域相对于window的位置,而第二段代码

表示,在greyView中,其子视图yellowView的frame区域,相对于window的位置

第三种(FromView)

CGRect rec1 = [self.view.window convertRect:self.yellowView.bounds fromView:self.yellowView];
总结:
toView就是从左往右开始读代码,也是从左往右理解意思

fromView就是从右往左开始读代码,也是从右往左理解意思

-
A
(CGPoint)convertPoint:B(CGPoint)point toView:C(nullable
UIView *)view;
- A(CGPoint)convertPoint:B(CGPoint)point fromView:C(nullable
UIView *)view;
第一句代表
A区域里面有个坐标B,需要把相对于A的坐标B转换成相对于C的坐标

第二句代表

从C区域里面转换坐标B,需要把相对于C的坐标转换成相对于A的坐标

理解下用起来真的蛮不错哦









内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐