天天看点

[iOS]UIView中的坐标转换

// 将像素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(contentView) 的 frame 转换 到  controller 中

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    CGRect rect = [cell convertRect:cell.contentView.frame toView:self.view];
    CGRect rect1 = [self.view convertRect:cell.textLabel.frame fromView:cell];
    
    NSLog(@"%@---%@",NSStringFromCGRect(rect),NSStringFromCGRect(rect1));
    
    CGPoint point = [self.view convertPoint:cell.contentView.center fromView:cell.contentView];
    
    CGPoint point1 = [cell.contentView convertPoint:cell.contentView.center toView:self.view];
    NSLog(@"%@>>>%@",NSStringFromCGPoint(point),NSStringFromCGPoint(point1));
           

输出

UIViewTest[10444:760134] {{0, 0}, {375, 43.5}}---{{0, 0}, {0, 0}}
UIViewTest[10444:760134] {187.5, 21.75}>>>{187.5, 21.75}
           

demo下载

继续阅读