iPhone - catch UIButton events when kept pressed
I'd like to catch the events of a pressed UIButton each 0.2 sec. I mean, I want to make the IBAction dedicated to the but开发者_Python百科ton to be triggered each 0.2 sec when the UIButton is kept pressed. I've tried some code found on the net and I understand I need to use a timer. But doing this, I loose the "sender" attribute that I need in my catch method.
How may I achieve to do this ?
When you create a NSTimer
you can attach custom object to it as userInfo field (e.g. check docs for +scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
method - userInfo parameter).
So you can pass your sender using userInfo
field.
You don't have to use a timer, you can implement the:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
events for the button.
You can do something like this if you expect the button to be pressed at the order of seconds:
#import <Foundation/Foundation.h>
@interface FancyButton: UIButton
{
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event ;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
@end
#import "FancyButton.h"
NSTimeInterval buttonPressedTime;
@implementation FancyButton
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
buttonPressedTime = [event timestamp];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if([event timestamp] - buttonPressedTime) > your_desired_press_time)
{
[self your_fancy_message]; // or any other processing you will do
}
buttonPressedTime = 0;
}
@end
I hope it helps.
If your timer is set up and working properly, all you need is some sort of reference to the button that was pressed. You can make an iVar in your class, along with a property, and set it in the touchDownInside event handler. Then check that in the timer method.
I could probably offer better advice if I saw some code, but when you schedule a selector to fire, you can designate a target object. As long as the object can access your sender, you're good.
What I would do in your case (if I understand you correctly) is keep the target object updated with the sender: when the UIButton is pressed, update the target object with the UIButton.
精彩评论