大部分內(nèi)容轉(zhuǎn)自
http://greenchiu.github.io/blog/2014/09/01/memo-the-uiview-convertrect/
如下兩個方法的區(qū)別:
convertRect:fromView:
convertRect:toView:
-
舉個例子:
當碰到需要將一個BView中的是一個CView位置(CView's frame),要被轉(zhuǎn)移到另一個AView上的實惠,要讓視覺上的位置保持不變,配合下面的圖片來服用。
image
圖中有三個View分別為A,B,C
B是A的subView,
C是B的subView,
這時我們要將C轉(zhuǎn)移到A,
參考下圖(我先把B隱藏起來)
這時就可以使用convertRect:toView:來取得新的frame給C
newFrame = [viewB convertRect:viewC.frame toView:viewA];

image
在將
C直接轉(zhuǎn)移到A后(C是A的subView),我們想把B加入到C里面,視覺位置依然保持不變,這時B的frame是對應(yīng)A的,想要取得B在C應(yīng)該有的位置,就使用convertRect:fromView
newFrame = [viewC convertRect:viewB.frame fromView:viewA];

image
以下是一些常用的轉(zhuǎn)換方法:
// 將像素point由point所在視圖轉(zhuǎn)換到目標視圖view中,返回在目標視圖view中的像素值
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
// 將像素point從view中轉(zhuǎn)換到當前視圖中,返回在當前視圖中的像素值
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
// 將rect由rect所在視圖轉(zhuǎn)換到目標視圖view中,返回在目標視圖view中的rect
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
// 將rect從view中轉(zhuǎn)換到當前視圖中,返回在當前視圖中的rect
// 例如把UITableViewCell中的subview(btn)的frame轉(zhuǎn)換到VC中
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
例如:controllerA中有一個UITableView,UITableView里有多行UITableVieCell,cell上放有一個button
// 在controllerA中實現(xiàn):
CGRect rc = [cell convertRect:cell.btn.frame toView:self.view];
或者
CGRect rc = [self.view convertRect:cell.btn.frame fromView:cell];
