ios开发 convertPoint 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;//矩形转换

二、例子

蓝色视图A放在self.view,灰色视图B放入self.vew,红色视图C放入灰色视图B


效果图
  • 蓝色A视图相对于self.view的frame为 (0, 100, 400, 500)
  • 灰色B视图相对于self.view的frame为 (0, 150, 300, 400)
  • 红色C相对于灰色B的fame的位置为 (0, 0, 80, 80)
UIButton *buttonA = [UIButton buttonWithType:(UIButtonTypeCustom)];
    buttonA.frame = CGRectMake(0, 100, 400, 500);
    buttonA.tag = 1001;
    buttonA.userInteractionEnabled = NO;
    buttonA.backgroundColor = [UIColor blueColor];
    [buttonA addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:buttonA];
    
    
    UIButton *buttonB = [UIButton buttonWithType:(UIButtonTypeCustom)];
    buttonB.frame = CGRectMake(0, 150, 300, 400);
    buttonB.tag = 1002;
   // buttonB.userInteractionEnabled = NO;
    buttonB.backgroundColor = [UIColor grayColor];
    [buttonB addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:buttonB];
    
    
    UIButton *buttonC = [UIButton buttonWithType:(UIButtonTypeCustom)];
    buttonC.frame = CGRectMake(0, 0, 80, 80);
    buttonC.tag = 1003;
    buttonC.backgroundColor = [UIColor redColor];
    //buttonC.userInteractionEnabled = NO;
    [buttonC addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [buttonB addSubview:buttonC];
    
  1. 需求1:求红色c的中心点相对于self.view的位置
CGPoint redCenterInView = [buttonB convertPoint:buttonC.center toView:self.view];
    NSLog(@"00 - %@",NSStringFromCGPoint(redCenterInView));
//  00 - {40, 190}
    CGPoint redCenterInView1 = [self.view convertPoint:buttonC.center fromView:buttonB];
// 11 - {40, 190}
    
    NSLog(@"11 - %@",NSStringFromCGPoint(redCenterInView1));
  1. 需求2:求红色c相对于self.view的坐标
CGRect redCenterInViewRect = [buttonB convertRect:buttonC.bounds toView:self.view];
    NSLog(@"22 - %@",NSStringFromCGRect(redCenterInViewRect));
  //22 - {{0, 150}, {80, 80}}
    CGRect redCenterInView1Rect = [self.view convertRect:buttonC.bounds fromView:buttonB];
    
    NSLog(@"33 - %@",NSStringFromCGRect(redCenterInView1Rect));
    //33 - {{0, 150}, {80, 80}}

你可能感兴趣的:(ios开发 convertPoint convertRect)