UIView中的坐标转换

大部分内容转自
http://greenchiu.github.io/blog/2014/09/01/memo-the-uiview-convertrect/

  • 如下两个方法的区别:

  • convertRect:fromView:

  • convertRect:toView:

  • 举个例子:
    当碰到需要将一个BView中的是一个CView位置(CView's frame),要被转移到另一个AView上的实惠,要让视觉上的位置保持不变,配合下面的图片来服用。

    UIView中的坐标转换_第1张图片
    image

    图中有三个View分别为ABC
    BAsubView
    CBsubView
    这时我们要将C转移到A
    参考下图(我先把B隐藏起来)
    这时就可以使用convertRect:toView:来取得新的frame给C

newFrame = [viewB convertRect:viewC.frame toView:viewA];

UIView中的坐标转换_第2张图片
image

在将 C直接转移到 A后( CAsubView),我们想把 B加入到 C里面,视觉位置依然保持不变,这时 Bframe是对应 A的,想要取得B在C应该有的位置,就使用 convertRect:fromView

newFrame = [viewC convertRect:viewB.frame fromView:viewA];
UIView中的坐标转换_第3张图片
image

以下是一些常用的转换方法:
// 将像素point由point所在视图转换到目标视图view中,返回在目标视图view中的像素值
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;

// 将像素point从view中转换到当前视图中,返回在当前视图中的像素值
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;

// 将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;

// 将rect从view中转换到当前视图中,返回在当前视图中的rect
// 例如把UITableViewCell中的subview(btn)的frame转换到VC中
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
例如:controllerA中有一个UITableView,UITableView里有多行UITableVieCell,cell上放有一个button
// 在controllerA中实现:
CGRect rc = [cell convertRect:cell.btn.frame toView:self.view];
或者
CGRect rc = [self.view convertRect:cell.btn.frame fromView:cell];

你可能感兴趣的:(UIView中的坐标转换)