一、首先来看看一下我们的需求
- 将
yellowView
(黄色view)所在的frame转换为blueView
(蓝色view)所在的frame
二、废话不多说,直接上代码代码
- 首先我们创建三个view,并且让
redView
作为blueView
子view,yellowView
作为redView
子view
// 创建blueView
UIView *blueView = [[UIView alloc] init];
blueView.backgroundColor = [UIColor blueColor];
blueView.frame = CGRectMake(30, 30, 200, 200);
[self.view addSubview:blueView];
self.blueView = blueView;
// 创建redView
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
redView.frame = CGRectMake(10, 20, 100, 100);
[blueView addSubview:redView];
self.redView = redView;
// 创建yellowView
UIView *yellowView = [[UIView alloc] init];
yellowView.backgroundColor = [UIColor yellowColor];
yellowView.frame = CGRectMake(10, 20, 50, 50);
[redView addSubview:yellowView];
self.yellowView = yellowView;
显示的结果就是上面的截图
- 重写控制器的
touchesBegan:withEvent:
方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"oldFrame -- %@", NSStringFromCGRect(self.yellowView.frame));
}
打印原始yellowView
frame为:
开始坐标系转换
- 使用
convertRect:toView:
转换坐标系
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 获取self.yellowView 在self.blueView 的坐标
CGRect newFrame = [self.yellowView convertRect:self.yellowView.bounds toView:self.blueView];
NSLog(@"%@", NSStringFromCGRect(newFrame));
}
可以看到打印结果为:
- 我们也可以借助
redView
为突破点
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 获取self.yellowView 在self.blueView 的坐标
// CGRect newFrame = [self.yellowView convertRect:self.yellowView.bounds toView:self.blueView];
// 这句话可以理解为:self.yellowView.frame是在redView坐标系,所以转换的时候,得使用self.redView
CGRect newFrame = [self.yellowView.superview convertRect:self.yellowView.frame toView:self.blueView];
NSLog(@"%@", NSStringFromCGRect(newFrame));
}
- 使用
convertRect:fromView:
转换坐标系
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 获取self.yellowView 在self.blueView 的坐标
// CGRect newFrame = [self.yellowView convertRect:self.yellowView.bounds toView:self.blueView];
// 这句话可以理解为:self.yellowView.frame是在redView坐标系,所以转换的时候,得使用self.redView
// CGRect newFrame = [self.yellowView.superview convertRect:self.yellowView.frame toView:self.blueView];
CGRect newFrame = [self.blueView convertRect:self.yellowView.bounds fromView:self.yellowView];
NSLog(@"%@", NSStringFromCGRect(newFrame));
}
可以看到,打印结果是一样的
总结
convertRect:toView:
就是将某个view的frame转为toView
的frame
convertRect:fromView:
就是从fromView
的frame转为调用这个方法的view的frame