【发布时间】:2011-05-30 12:23:44
【问题描述】:
我试图找到一种方法来识别触摸并按住我的按钮。我认为子类化我的按钮是个好主意,但我现在正在为子类、parentviews 和 viewcontroller 的整个想法而苦苦挣扎。所以请原谅,我担心这是一个初学者的问题:
如何从子类 UIButton 调用方法(我已在 ViewController 中定义)?
- [自我某种方法];不起作用 - 因为 UIButton 不是我的 ViewController 的后代。
- [super someMethod];也不起作用 - 我想同样的问题
- [self.superview someMethod]; ...再次没有运气
- [MyViewController someMethod];也不起作用——因为它是“未清除”——我必须导入我的 ViewController 吗?或者进行某种协议/类调用?
非常感谢任何帮助。
这是我的子类:
//
// 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
【问题讨论】:
标签: iphone objective-c cocoa-touch uibutton subclass