重写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&gt;

@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&gt;


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

原文地址:https://blog.csdn.net/qq_43441647/article/details/126439822

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_48306.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注