坐标转换,可以用UIVIew的方法

//由要转换坐标view的superView执行该方法,rect为待转换view的frame,view是要显示到哪儿的
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;

//由要转换到哪儿的view执行,rect为待转换view的frame,view是待转换view的superView
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;

来计算同一组件在不同view下的坐标。示例如下

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 100, kScreenWidth, 200)];
    grayView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:grayView];
    
    UIView *brownView = [[UIView alloc]initWithFrame:CGRectMake(10, 20, 50, 50)];
    brownView.backgroundColor = [UIColor brownColor];
    [grayView addSubview:brownView];
    
    CGRect sonRectInController = [brownView.superview convertRect:brownView.frame toView:self.view];
    CGRect sonRectInController2 = [self.view convertRect:brownView.frame fromView:brownView.superview];
    NSLog(@"自己的%@", NSStringFromCGRect(brownView.frame));
    NSLog(@"父类的%@", NSStringFromCGRect(sonRectInController));
    NSLog(@"父类的2%@", NSStringFromCGRect(sonRectInController2));
}

效果如下

posted on 2016-11-24 11:54  lixin327  阅读(525)  评论(0编辑  收藏  举报