項目中常有需獲取單獨某一控件或試圖在其父視圖中的坐標尺寸的相關需求。
可通過下方方法獲取控件在父視圖的固定坐標系
以下兩種方法相同
CGRect rect=[cell convertRect:cell.textView.bounds toView:self.tableView];
CGRect rect = [self.tableView convertRect:cell.textView.bounds fromView:cell];
層級關系
cell.textView->
cell->
self.tableView(父視圖)
- 示例
//獲取某個cell在當前tableView上的坐標位置
CGRect rectInTableView=[tableView rectForRowAtIndexPath:indexPath];
//獲取cell在當前屏幕的位置
CGRect rectInSuperView=[tableView convertRect:rectInTableView toView:[tableView superview]];
//獲取cell在當前collection的位置
CGRect cellInCollectionView = [collectionView convertRect:item.frame toView:collectionView];
UICollectionViewCell * item = [collectionView cellForItemAtIndexPath:indexPath]];
//獲取cell在當前屏幕的位置
CGRect cellInSuperview = [collectionView convertRect:item.frame toView:[collectionView superview]];
而如果要求在頁面滑動到某一控件處或者控件滑動到window頁面某一坐標點處時需顯示或進行某些操作,可以將toView設定為window,這時在scrollViewDidScroll中顯示的坐標即為控件在當前頁面的坐標
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
CGRect rect=[self.textView convertRect:self.textView.bounds toView:window];
if (rect.origin.y<SCREEN_HEIGHT) {
[self.textView becomeFirstResponder];
}
}
轉換像素點
// 將像素point由point所在視圖轉換到目標視圖view中,返回在目標視圖view中的像素值
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
// 將像素point從view中轉換到當前視圖中,返回在當前視圖中的像素值
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
[
fromViewconvertPoint:pointtoView:toView];
[toViewconvertPoint:pointfromView:fromView];
轉換Rect
// 將rect由rect所在視圖轉換到目標視圖view中,返回在目標視圖view中的rect
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
// 將rect從view中轉換到當前視圖中,返回在當前視圖中的rect
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
[
fromViewconvertRect:recttoView:toView];
[toViewconvertRect:rectfromView:fromView];
手指在UIScrollView上的滑動速率、方向以及移動距離
// velocityInView: 手指在視圖上移動的速度(x,y), 正負也是代表方向,值得一體的是在絕對值上|x| > |y| 水平移動, |y|>|x| 豎直移動。
CGPoint velocity = [scrollView.panGestureRecognizer velocityInView:scrollView];
//translationInView : 手指在視圖上移動的位置(x,y)向下和向右為正,向上和向左為負。X和Y的數值都是距離手指起始位置的距離
CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];