[10秒学会] - iOS UIView中的坐标转换 convertRect

本文通过实例演示了如何使用UIKit中的UIView方法convertRect:toView:进行视图坐标转换,并展示了如何将按钮从一个视图坐标系转换到另一个视图坐标系中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:我是赵大财,10秒学会系列,绝不废话连篇! 力求10秒,让你了解 会用该 知识点

效果图:005517_wZVx_1186234.png


直接上代码

    UIView *viewA = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
    viewA.backgroundColor = [UIColor redColor];
    UIButton *btnA = [UIButton buttonWithType:UIButtonTypeCustom];
    btnA.frame = CGRectMake(30, 30, 20, 20);
    btnA.backgroundColor = [UIColor yellowColor];
    
    
    UIView *viewB = [[UIView alloc]initWithFrame:CGRectMake(10, 200, 100, 100)];
    viewB.backgroundColor = [UIColor blueColor];
    //====上下2种方式 等价====
    //CGRect rcA = [viewA convertRect:btnA.frame fromView:viewA];
    //CGRect rcB = [self.view convertRect:btnA.frame fromView:viewA];
    
    CGRect rcA = [viewA convertRect:btnA.frame toView:viewA];
    CGRect rcB = [viewA convertRect:btnA.frame toView:self.view];
    
    UIButton *btnB = [UIButton buttonWithType:UIButtonTypeCustom];
    btnB.frame = rcA;
    btnB.backgroundColor = [UIColor yellowColor];
    
    UIButton *btnC = [UIButton buttonWithType:UIButtonTypeCustom];
    btnC.frame = rcB;
    btnC.backgroundColor = [UIColor yellowColor];
    
    [self.view addSubview:viewA];
    [viewA addSubview:btnA];
    [self.view addSubview:viewB];
    [viewB addSubview:btnB];
    [viewB addSubview:btnC];


转载于:https://my.oschina.net/zhaodacai/blog/652465

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值