1)向您的 UIButton 添加一个类别
2)向该类别添加新属性
3)添加您的方法以初始化后退按钮
4)覆盖-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
5)子类 toolBarItems
@implementation UIButton (yourButtonCategory)
@dynamic shouldHitTest; // boolean
@dynamic hitTestRect; // enlarge rect of the button
@dynamic buttonPressedInterval; // interval of press, sometimes its being called twice
-(id)initBackBtnAtPoint:(CGPoint)_point{
// we only need the origin of the button since the size and width are fixed so the image won't be stretched
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); // this will be the enlarge frame of the button
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;
// not the event we were interested in
} else {
// use this call
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)];
希望能帮助到你