I was trying to find a way to recognise a touch&hold on my buttons. I thought that to subclass my buttons was a good idea, but I'm now struggling with the whole idea of subclasses, parentsviews and the viewcontroller. So please forgive, I fear that this is a beginner's question:
How do I call a method (which I've defined in my ViewController) from a subclassed UIButton?
- [self someMethod]; doesn't work - as UIButton is not a descendent of my ViewController.
- [super someMethod]; doesn't work either - same problem I suppose
- [self.superview someMethod]; ... again no luck
- [MyViewController someMethod]; doesn't work either -- as it is 'undecleared' -- do I have to import my ViewController? Or do some kind of protocol/class call?
Any help would be very much appreciated.
Here is my subclass:
//
// MoleButton.h
//
#import <Foundation/Foundation.h>
@interface MoleButton : UIButton {
int page;
NSString *colour;
UIViewController *theViewController;
NSTimer *holdTimer;
}
@property (nonatomic, assign) int page;
@property (nonatomic, assign) NSString *colour;
@end
//
// MoleButton.m
#import "MoleButton.h"
@implementation MoleButton
@synthesize page, colour;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[self.superview touchesBegan:touches withEvent:event];
[holdTimer invalidate];
holdTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(touchWasHeld) userInfo:nil repeats:NO];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
[self.superview touchesMoved:touches withEvent:event];
[holdTimer invalidate];
holdTimer = nil;
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
[self.superview touchesEnded:touches withEvent:event];
}
- (void)touchWasHeld
{
holdTimer = nil;
// do your "held" behavior here
NSLog(@"TOUCH WAS HELD!!!!");
[self.theViewController doSomething];
}
@end