Search code examples
iostouchesbegan

how to detect touchesbegan touchesended for UIBarButtonItem?


I am using an UIBarButtonItem in order to trigger events. I use the integrated InterfaceBuider in xcode4 to create my UIBarButtonItem and then I connected the button to a method in my view controller. The method looks like this:

-(IBAction)NoteOnOff:(id)sender
{
    UIButton *button = (UIButton*)sender;

   /* now perform action */
}

Now I want to also detect fingerdown/fingerup because I want to trigger noteon/noteoff types of event for a midi synth kind of app.

1- Is there a way to detect if sender has been pressed down or up in the above method?

2- I tried to subclass UIBarButtonItem and implement touchesBegan and touchesEnded this way:

@interface myUIBarButtonItem : UIBarButtonItem {

}

@end

@implementation myUIBarButtonItem

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touchesBegan");
NSLog(@"touches=%@,event=%@",touches,event);
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touchesEnded");
NSLog(@"touches=%@,event=%@",touches,event);
}

@end

Then I changed the class of the UIBarButtonItem to myUIBarButtonItem in the interface editor but no luck. Is that the correct way of using my customized class in the interface editor?

3- I read somewhere that UIBarButtonItem does not inherit from UIResponder so they can't intercept touchesbegan/touchesended events. If that is the case then what is the proper way to be able to detect touches down and touches up events? I am mostly a C/C++ programmer and my knowledge is pretty limited about objective C and the iphone environement. I only know how to use the UI editor and I do not know how create custom UIs and use them without this editor yet.

Bottom line is: what is the simplest way to detect touchdown/touchup with the lest latency possible?

Any pointers to tutorial or docs is also welcome.

Thanks,

Baba


Solution

  • You can do it like this (no need to subclass UIBarButtonItem):

    [button addTarget:self action:@selector(touchUp:)
      forControlEvents:UIControlEventTouchUpInside];
    
    [button addTarget:self action:@selector(touchDown:)
      forControlEvents:UIControlEventTouchDown];
    
    - (void) touchUp:(id)sender {
    }
    
    - (void) touchDown:(id)sender {
    }