1) Add a category to your UIButton
2) Add new properties to the category
3) Add your method to initialise the back button
4) Override -(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
5) Subclass 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
Lets say the touch event doesn't trigger we need the view its in to call the button so in toolBarItems we do something like:
-(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];
}
}
}
then thats it. we enlarge the frame without enlarging the actual button.
you just initial your button like: UIButton *btn = [[UIButton alloc]initBackBtnAtPoint:CGPointMake(0,0)];
Hope it helps