當我們想找到一個視圖的子視圖相對于當前控制器中的坐標位置時,用坐標轉換就可以很方便的找到了,如下圖所示:
如圖所示:從下到上依次是 self.view --> redView -->yellowView
redView的坐標:{{20, 20}, {335, 627}},加在控制器的view上
yellowView的坐標:{{20, 20}, {295, 587}},加在redView上
CGSize size = self.view.frame.size;
UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, size.width - 40, size.height - 40)];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
UIImageView *yellowView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, redView.frame.size.width - 40, redView.frame.size.height - 40)];
yellowView.backgroundColor = [UIColor yellowColor];
[redView addSubview:yellowView];
NSLog(@"%@ --- %@", NSStringFromCGRect(redView.frame), NSStringFromCGRect(yellowView.frame));
//? ? 輸出{{20, 20}, {335, 627}} --- {{20, 20}, {295, 587}}
//把 yellowView.frame 從 redView 的坐標系轉換到 self.view 的坐標系
// 如果傳入的是 yellowView.frame,則要用 yellowView 的父視圖來調用,toView:傳入的參數是最終要轉換到的那個視圖。
//? ? CGRect rect = [redView convertRect:yellowView.frame toView:self.view];? ? // 這個和下面一句一樣
// 如果傳入的是 yellowView.bounds,則要用 yellowView 本身來調用,toView:傳入的參數是最終要轉換到的那個視圖。
CGRect rect = [yellowView convertRect:yellowView.bounds toView:self.view]; // 這個和上面一句一樣
CGRect frame = [self.view convertRect:yellowView.frame fromView:redView];
NSLog(@"%@, %@", NSStringFromCGRect(rect), NSStringFromCGRect(frame));
//? ? 輸出{{40, 40}, {295, 587}}, {{40, 40}, {295, 587}}
//把 yellowView.frame.origin 從 redView 的坐標系轉換到 self.view 的坐標系
CGPoint point = [redView convertPoint:yellowView.frame.origin toView:self.view];
CGPoint point1 = [self.view convertPoint:yellowView.frame.origin fromView:redView];
NSLog(@"%@, %@", NSStringFromCGPoint(point), NSStringFromCGPoint(point1));
// 輸出{40, 40}, {40, 40}
?