视图间坐标转换

一、方法

- (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;

 

二、理解

例子1:[V1 convertPoint:point toView:V2] == [V2 convertPoint:point fromView:V1]

例子2:[aView convertPoint:p toView:anotherView]

将p『相对aView的坐标』转换为『相对anotherView的坐标』

比如说aView是原点(0,0),anotherView是aView的子视图,原点是(100, 0)

那么一个在anotherView中坐标是(0, 0)的点经过转换后在aView的坐标是(100, 0)

 

三、注意 

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来处理的,但是并不确定。 
   所以一定要小心。

posted on 2016-03-27 02:32  Wilson_CYS  阅读(329)  评论(0编辑  收藏  举报

导航