当按钮超过了父视图范围,点击是没有反应的。因为消息的传递是从最下层的父视图开始调用hittest方法。
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
UIView *view = [super hitTest:point withEvent:event];
return view;
}
当存在view时才会传递对应的event,现在点击了父视图以外的范围,自然返回的是nil。所以当子视图(比如按钮btn)因为一些原因超出了父视图范围,就要重写hittest方法,让其返回对应的子视图,来接收事件。
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
UIView *view = [super hitTest:point withEvent:event];
if (view == nil) {
CGPoint tempoint = [btn convertPoint:point fromView:self];
if (CGRectContainsPoint(btn.bounds, tempoint))
{
view = btn;
}
}
return view;
}
超越点击事件
//
// UIButton+TapScope.m
// SuningSummer
//
// Created by snping on 14-8-15.
// Copyright (c) 2014年 Suning. All rights reserved.
//
#import "UIButton+TapScope.h"
#import <objc/runtime.h>
static void * kHitEdgeInsetsKey = &kHitEdgeInsetsKey;
@implementation UIButton (TapScope)
- (void)setHitEdgeInsets:(UIEdgeInsets)hitEdgeInsets
{
NSValue *value = [NSValue valueWithUIEdgeInsets:hitEdgeInsets];
objc_setAssociatedObject(self, kHitEdgeInsetsKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIEdgeInsets)hitEdgeInsets
{
NSValue * value = objc_getAssociatedObject(self, kHitEdgeInsetsKey);
if(value) {
return [value UIEdgeInsetsValue];
}
return UIEdgeInsetsZero;
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
if (UIEdgeInsetsEqualToEdgeInsets(self.hitEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
return [super pointInside:point withEvent:event];
}
CGRect hitFrame = UIEdgeInsetsInsetRect(self.bounds, self.hitEdgeInsets);
return CGRectContainsPoint(hitFrame, point);
}