解决子视图超出父视图无法响应问题

前言

在日常开发过程中,难免都会遇到子控件超过父视图的情况。超出父视图的部分是不能响应点击事件,但是总有些情况需要我们让超出的部分响应点击事件,那么就需要用到convertPoint。

convertPoint相关的方法

  • 转换像素点
// 将像素point由point所在视图转换到目标视图view中,返回在目标视图view中的像素值
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;

// 将像素point从view中转换到当前视图中,返回在当前视图中的像素值
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
  • 转换Rect
// 将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;

// 将rect从view中转换到当前视图中,返回在当前视图中的rect
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;

问题描述

一个自己定义View,这个View中有一个UIButton,但是这个UIButton超出父视图一部分。
在这里插入图片描述
红色的是父视图,绿色的是子视图,是一个按钮。部分超过了红色视图。
代码如下:

#import "TestView.h"

@implementation TestView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor redColor];
        
        self.button = [[UIButton alloc]initWithFrame:CGRectMake(0, -40, frame.size.width, 80)];
        self.button.backgroundColor = [UIColor greenColor];
        
        [self addSubview:self.button];
        
        [self.button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        self.clipsToBounds = NO;
    }
    return self;
}

- (void)buttonClick:(UIButton *)sender{
    NSLog(@"有输出");
}
// 解决UIButton超出父视图不能响应问题
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    CGPoint newPoint = [self convertPoint:point toView:self.button];
    
    if ([self.button pointInside:newPoint withEvent:event]) {
        return self.button;
    }
    return [super hitTest:point withEvent:event];
}

解决方案

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    CGPoint newPoint = [self convertPoint:point toView:self.button];
    
    if ([self.button pointInside:newPoint withEvent:event]) {
        return self.button;
    }
    return [super hitTest:point withEvent:event];
}

如有疑问可以联系我。谢谢浏览本文章。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值