iOS子视图超出父视图的frame,点击无法响应的解决方案

重写hitTest方法

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {

    CGPoint newPoint = [self convertPoint:point toView:self.childrenBtn];

        if ([self.childrenBtn pointInside:newPoint withEvent:event]) {

            return self.childrenBtn;

        }

        return [super hitTest:point withEvent:event];

}

源代码如下

ViewController.h:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController



@end

ViewController.m:

#import "ViewController.h"

#import "View.h"

#define kwidth [UIScreen mainScreen].bounds.size.width

#define kheight [UIScreen mainScreen].bounds.size.height



@interface ViewController ()



@end



@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    View *view1 = [[View alloc] initWithFrame:CGRectMake(0, 0, kwidth, kheight)];

    [self.view addSubview:view1];

    // Do any additional setup after loading the view.

}

View.h:

#import <UIKit/UIKit.h>


NS_ASSUME_NONNULL_BEGIN


@interface View : UIView


@end


NS_ASSUME_NONNULL_END

View.m:

#import "View.h"
#define kwidth [UIScreen mainScreen].bounds.size.width

@interface View ()

@property (nonatomic, strong) UIButton *fatherBtn;
@property (nonatomic, strong) UIButton *childrenBtn;

@end

@implementation View

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self viewDidLoad];
    }
    return self;
}

- (void)viewDidLoad {
    CGFloat imagex = (kwidth - 200) / 2;
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(imagex, 100, 200, 400)];
    [self addSubview:btn];
    self.fatherBtn = btn;
    self.fatherBtn.backgroundColor = [UIColor blackColor];
    [self.fatherBtn addTarget:self action:@selector(fatherBtnClick) forControlEvents:UIControlEventTouchUpInside];

    UIButton *btn2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 250, 80)];
    [btn addSubview:btn2];
    self.childrenBtn = btn2;
    self.childrenBtn.backgroundColor = [UIColor redColor];
    [self.childrenBtn addTarget:self action:@selector(childrenBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

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

- (void)fatherBtnClick {
    NSLog(@"点击了fatherBtn");
}

- (void)childrenBtnClick {
    NSLog(@"点击了childrenBtn");
}

@end
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值