UIView的提供了这个方法:- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
1.创建CustomView继承自UIView :
CustomView.h
@property (strong,nonatomic)NSArray * passthroughViews;
@property (nonatomic)BOOL testHits;
-(BOOL) isPassthroughView: (UIView*) view;
CustomView.m
-(UIView*) hitTest:(CGPoint)point withEvent:(UIEvent *)event{
if(self.testHits){
return nil;
}
if(!self.passthroughViews
|| (self.passthroughViews && self.passthroughViews.count == 0)){
return self;
} else {
UIView *hitView = [super hitTest:point withEvent:event];
if (hitView == self) {
self.testHits = YES;
CGPoint superPoint = [self.superview convertPoint:point fromView:self];
UIView *superHitView = [self.superview hitTest:superPoint withEvent:event];
self.testHits = NO;
if ([self isPassthroughView:superHitView]) {
hitView = superHitView;
}
}
return hitView;
}
}
- (BOOL)isPassthroughView:(UIView *)view {
if (view == nil) {
return NO;
}
if ([self.passthroughViews containsObject:view]) {
return YES;
}
return [self isPassthroughView:view.superview];
}
2.创建ViewController继承自UIViewController :
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.passthroughButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.passthroughButton setTitle:@"Passthrough" forState:UIControlStateNormal];
[self.view addSubview:self.passthroughButton];
self.passthroughButton.frame = CGRectMake(20, 50, 120, 28);
[self.passthroughButton addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
CustomView *customView = [[CustomView alloc] initWithFrame:CGRectMake(80, 10, 300, 200)];
customView.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:.5];
//customView.passthroughViews = [NSArray arrayWithObject:self.passthroughButton];
[self.view addSubview:customView];
}