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

开发过程中,我们经常会判断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(nullableUIView *)view;

- A(CGPoint)convertPoint:B(CGPoint)point fromView:C(nullableUIView *)view;

第一句代表

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

第二句代表

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

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




  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值