1)为您的UIButton添加一个分类
2)为该分类添加新属性
3)添加初始化后退按钮的方法
4)覆盖-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
5)子类化toolBarItems
@implementation UIButton (yourButtonCategory)
@dynamic shouldHitTest;
@dynamic hitTestRect;
@dynamic buttonPressedInterval;
-(id)initBackBtnAtPoint:(CGPoint)_point{
self = [self initWithFrame:CGRectMake(_point.x, _point.y, 28, 17)];
[self setBackgroundImage:[UIImage imageNamed:@"back-button.png"]forState:UIControlStateNormal];
self.shouldHitTest = CGRectMake(self.frame.origin.x - 25, self.frame.origin.y-10, self.frame.size.width+25, self.frame.size.height+25);
self.shouldHitTest = YES;
return self;
}
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
BOOL shouldReturn = [super pointInside:point withEvent:event];
NSSet *touches = [event allTouches];
BOOL shouldSendTouches = NO;
for (UITouch *touch in touches) {
switch (touch.phase) {
case UITouchPhaseBegan:
shouldSendTouches = YES;
break;
default:
shouldSendTouches = NO;
break;
}
}
if(self.shouldHitTest){
double elapse = CFAbsoluteTimeGetCurrent();
CGFloat totalElapse = elapse - self.buttonPressedInterval;
if (totalElapse < .32) {
return NO;
} else {
if(CGRectContainsPoint(self.hitTestRect, point)){
if(shouldSendTouches){
self.buttonPressedInterval = CFAbsoluteTimeGetCurrent();
[self sendActionsForControlEvents:UIControlEventTouchUpInside];
}
return NO;
}
}
}
return shouldReturn;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
CGPoint touch_point = [touch locationInView:self];
[self pointInside:touch_point withEvent:event];
}
@end
假设触摸事件未被触发,我们需要调用其所在的视图中的按钮,因此在toolBarItems中,我们需要执行以下操作:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
for(id subs in self.subviews){
if([subs isKindOfClass:[UIButton class]]){
[subs touchesBegan:touches withEvent:event];
}
}
}
那么就这样了。我们扩大框架而不扩大实际按钮。
您只需要像这样初始化您的按钮:UIButton *btn = [[UIButton alloc]initBackBtnAtPoint:CGPointMake(0,0)];
希望能帮到您。