重写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