坐标转换convertRect,从此不再迷糊

坐标转换在开发中经常使用,有时容易搞混,最近正好搞了一次,记录一下...

- (CGPoint)convertPoint:(CGPoint)point toView:(nullable UIView *)view;
- (CGPoint)convertPoint:(CGPoint)point fromView:(nullable UIView *)view;
- (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;
- (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;
//创建一个tabl
mTabl = [[UITableView alloc] initWithFrame:CGRectMake(0, 200, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-64-200) style:UITableViewStylePlain];

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;//cell的高度
}
//我们在cell上加一个控件
 if (![cell.contentView viewWithTag:1000]){
        UIView *subCellView = [[UIView alloc] initWithFrame:CGRectMake(100, 10, 200, 20)];
        subCellView.backgroundColor = [UIColor orangeColor];
        subCellView.tag = 1000;
        [cell.contentView addSubview:subCellView];
    }

点击第二个cell

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIView *subCellView = [cell.contentView viewWithTag:1000];
    CGRect subCellRect = [subCellView.superview convertRect:subCellView.frame toView:self.view];
    
    NSLog(@"%@ --- %@",NSStringFromCGRect(subCellView.frame),NSStringFromCGRect(subCellRect));

    subCellRect = [self.view convertRect:subCellView.frame fromView:subCellView.superview];
    
    NSLog(@"%@ --- %@",NSStringFromCGRect(subCellView.frame),NSStringFromCGRect(subCellRect));

2018-05-21 09:49:09.663619+0800 TestPosition[98777:2942237] {{100, 10}, {200, 20}} --- {{100, 315}, {200, 20}}
2018-05-21 09:49:09.663792+0800 TestPosition[98777:2942237] {{100, 10}, {200, 20}} --- {{100, 315}, {200, 20}}

image.png

我们来计算一下subview(tag为1000的view)相对于self.view的高度
200(tabl的Y) + 105(第一个cell的高度) + 10(相对于父视图的Y) = 315 (Y)
和输出的结果正好一致.

所以,使用 规则如下:

获取相对于self.view的坐标位置
 [subCellView.superview convertRect:subCellView.frame toView:self.view]
[self.view convertRect:subCellView.frame fromView:subCellView.superview]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 年轻人想在职场上有所作为,以下的三种职场心态就必须具有。 很多人都在说,今天的职场,是90后的天下。是的,作为职场...
    钱有多多阅读 2,844评论 0 0
  • 镀锌冲孔网板厂家@呼吁大家保护"枯枝花" 前段时间在花店里买了一束枯枝花,当时店员介绍这种花很神奇,外表干枯的枝子...
    镀锌冲孔网板钢格栅板厂家阅读 1,183评论 0 0
  • 一条鱼,住在沼泽里。 依附沼泽而生的是交错丛生的芒草,不知从哪儿吹来一阵夏日的风,透过原野的沉寂窥探着头顶的那抹蓝...
    夏日晓兮阅读 3,677评论 9 7
  • 公辅工程比较常见的水电气风,供热我常写,供冷真的不常见,既然碰到了就来研究下。 去企业看现场,不懂工艺还东问西问显...
    年年有胖骨阅读 4,617评论 0 0