iOS超出父控件范围无法点击问题解决

 更新时间:2023年06月26日 17:24:29   作者:萤火驻守心间  
这篇文章主要介绍了iOS超出父控件范围无法点击问题解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

场景

橙色view添加在蓝色view上,满足点击超出蓝色view部分可以响应事件

实现思路

重写底部蓝色view的hitTest方法,从最上层依次遍历子控件,判断触摸点是否在子控件上,在的话就返回子控件的hitTest方法,不在就返回self

完整代码

#import "ViewController.h"
#import "BotView.h"
@interface ViewController ()
@property(strong, nonatomic) BotView *botView;
@property(strong, nonatomic) UIView *topView;
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    self.botView = [BotView new];
    self.topView = [UIView new];
    [self.view addSubview:self.botView];
    [self.botView addSubview:self.topView];
    self.botView.frame = CGRectMake(100, 100, 100, 100);
    self.topView.frame = CGRectMake(0, 0, 50, 200);
    self.botView.backgroundColor = [UIColor linkColor];
    self.topView.backgroundColor = [UIColor orangeColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(topViewClick:)];
    [self.topView addGestureRecognizer:tap];
}
- (void)topViewClick:(UITapGestureRecognizer *)tap {
    NSLog(@"点击了顶部view");
}
@end

botView代码

#import "BotView.h"
@implementation BotView
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    int count = (int)self.subviews.count;
    for (int i=count-1; i>=0; i--) {
        UIView *subView = self.subviews[i];
        //点击事件作用在子控件上面,返回点击点
        CGPoint isPoint = [self convertPoint:point toView:subView];
        UIView *subv = [subView hitTest:isPoint withEvent:event];
        if (subv) {
            return subv;
        }
    }
    return self;
}
@end

以上就是iOS超出父控件范围无法点击问题解决的详细内容,更多关于iOS父控件无法点击的资料请关注程序员之家其它相关文章!

相关文章

最新评论

?


http://www.vxiaotou.com