iOS中的坐标转换

对于坐标转换,先看两个效果


iOS中的坐标转换_第1张图片
1.png
iOS中的坐标转换_第2张图片
2.png

需求:

点击关闭按钮弹出选择的关闭的理由
如果关闭按钮的位置(closeBtnY+closeBtnH)和屏幕底部(ScreenH)的距离(screenH-closeBtnY-closeBtnH)超过popView的高度(popViewH),popView就下方展示
如果screenH-closeBtnY-closeBtnH小于popViewH就在上方展示

分析:所以就需要知道cellcloseBnt在控制器的view的位置,需要将closeBtnframe转换到控制器view

对于坐标转换用到的方法:

// 将像素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; 

代码:

- (void)setupUI
{
    UIView * greenView          = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    greenView.backgroundColor   = [UIColor greenColor];
    self.greenView              = greenView;
    [self.view addSubview:self.greenView];
    
    UIView * orangeView         = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
    orangeView.backgroundColor  = [UIColor orangeColor];
    self.orangeView             = orangeView;
    [self.greenView addSubview:self.orangeView];
    
    // orangeView在view的位置应该是(100+50,100+50)
    CGPoint point = [self.greenView convertPoint:CGPointMake(50, 50) toView:self.view];
    NSLog(@"point = %@",NSStringFromCGPoint(point));
    
    CGPoint point1 = [self.view convertPoint:CGPointMake(50, 50) fromView:self.greenView];
    NSLog(@"point1 = %@",NSStringFromCGPoint(point1));
}

结果:

iOS中的坐标转换_第3张图片
3.png

总结:

方法调用视图,point的视图,toView/fromView视图,三者的关系:

point rect 是尺寸最小视图的point和rect,toView是尺寸最大的视图,fromeView是尺寸居中的视图

你可能感兴趣的:(iOS中的坐标转换)