美文网首页
坐标转换convertRect,从此不再迷糊

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

作者: 新生的光明 | 来源:发表于2018-05-21 10:00 被阅读0次

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

    - (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]
    

    相关文章

      网友评论

          本文标题:坐标转换convertRect,从此不再迷糊

          本文链接:https://www.haomeiwen.com/subject/xwtfjftx.html