我試圖找到一種方法來識別我的按鈕上的觸摸&。我認爲子類化我的按鈕是一個好主意,但我現在正在努力處理子類,父視圖和視圖控制器的整個想法。所以請原諒,我擔心這是一個初學者的問題:如何從子類UIButton調用viewController中的方法?
如何從子類UIButton調用方法(我在ViewController中定義)?
- [self someMethod];不起作用 - 因爲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
感謝這麼多,但究竟如何做呢? @property(nonatomic,retain)ViewController MyViewController?我是否通過#importing添加控制器? – 2011-05-30 12:30:07
你已經在你的子類UIButton中創建了屬性。添加另一個(UIViewController * myViewController),在初始化Button之後,添加viewController([yourbutton setMyViewController:self];並用[self.myViewConroller yourMessage]在你的UIButton子類中調用它; – cem 2011-05-30 12:32:27
非常感謝,但我沒有得到這個工作。我現在得到錯誤消息'訪問未知的viewController getter方法,當我調用[self.theViewController doSomething]; – 2011-05-30 13:03:43