iOS-- UIView中的坐标转换

来源:互联网 发布:长沙软件职业学院地址 编辑:程序博客网 时间:2024/05/18 01:24

// 将像素pointpoint所在视图转换到目标视图view中,返回在目标视图view中的像素值

- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;

// 将像素pointview中转换到当前视图中,返回在当前视图中的像素值

- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;


// rectrect所在视图转换到目标视图view中,返回在目标视图view中的rect

- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;

// rectview中转换到当前视图中,返回在当前视图中的rect

- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;


UITableViewCell中的subview(btn)frame转换 controllerA

// 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];

// rcbtncontrollerA中的rect


或当已知btn时:

CGRect rc = [btn.superview convertRect:btn.frame toView:self.view];

CGRect rc = [self.view convertRect:btn.frame fromView:btn.superview];





/////



convertPoint本身并不难理解,但是下面的这些特殊情况一定要注意,经过测试,总结如下: 

  UIView* fromView = [[UIViewalloc] init];

  [fromView convertPoint:aPoint toView:toView];


就是将fromView坐标系中的一个点转换为toView中的一个点。 

这时需要注意: 
1、如fromView是nil,则返回CGrectZero。 
   这种情况发生在view的init方法中; [self.superView convertPoint:aPoint toView:toView]; 
   此时的self.superView是nil。 
2、如果toView是nil则相当于:[fromView convertPoint:aPoint toView:selfView.window]; 
所以如果要将坐标转为相对于窗口的坐标,则只要如下就可以了: 
[fromView convertPoint:aPoint toView:nil]; 

3、fromView和toView还没有放到一个view中去,也就是没有对它们执行addSubview方法,此时它们的superView是nil。这种情况一定要小心了, 
   尽量不要这么作,因为view还没有建立明确的相对坐标系,这时cocoa框架一定很抓狂,作了很多假设,一般是以创建fromView和toView的那个view作为superView来处理的,但是并不确定。 
   所以一定要小心。
0 0
原创粉丝点击