// 將像素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
- (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];
// 此rc為btn在controllerA中的rect
或當已知btn時:
CGRect rc = [btn.superview convertRect:btn.frame toView:self.view];
或
CGRect rc = [self.view convertRect:btn.frame fromView:btn.superview];
UIView*greenView = [[UIViewalloc]initWithFrame:CGRectMake(10, 20, 100, 100)];
greenView.backgroundColor= [UIColorgreenColor];
[self.viewaddSubview:greenView];
UIView*redView = [[UIViewalloc]initWithFrame:CGRectMake(110, 120, 200, 200)];
redView.backgroundColor= [UIColorredColor];
[self.viewaddSubview:redView];
UIView*blueView = [[UIViewalloc]initWithFrame:CGRectMake(10, 20, 100, 100)];
[redViewaddSubview:blueView];
blueView.backgroundColor= [UIColorblueColor];
CGRectframe= [redViewconvertRect:blueView.frametoView:greenView];
UIView*overLapView1 = [[UIViewalloc]initWithFrame:frame];
[self.viewaddSubview:overLapView1];
overLapView1.backgroundColor= [UIColororangeColor];
在開發中我們經常會需要判斷兩個控件是否包含重疊,此時如果控件A和B的坐標原點如果不確定的話,那么肯定會導致比較不正確發生錯誤
判斷包含重疊的代碼如下:
CGRectContainsRect(<#CGRect rect1#>, <#CGRect rect2#>)
CGRectContainsPoint(<#CGRect rect#>, <#CGPoint point#>)
CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)
其中
CGRectContainsRect表示rect1和rect2是否有重疊
CGRectContainsPoint表示point是不是在rect上
CGRectIntersectsRect的意思是rect1是否包含了rect2
那么問題就來了,既然坐標原點不確定,那么能不能轉換A的坐標原點到B上呢?答案是可以的,具體實現代碼如下:
- (CGPoint)convertPoint:(CGPoint)point toView:(nullableUIView*)view;- (CGPoint)convertPoint:(CGPoint)point fromView:(nullableUIView*)view;// 后面就具體使用下面的代碼舉例,下面的會了,上面的自然也就會了- (CGRect)convertRect:(CGRect)rect toView:(nullableUIView*)view;- (CGRect)convertRect:(CGRect)rect fromView:(nullableUIView*)view;