2011-05-30 28 views
0

我試圖找到一種方法來識別我的按鈕上的觸摸&。我認爲子類化我的按鈕是一個好主意,但我現在正在努力處理子類,父視圖和視圖控制器的整個想法。所以請原諒,我擔心這是一個初學者的問題:如何從子類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 

回答

2

你可以簡單地在子類UIButton的類,它保存視圖控制器添加屬性。初始化它時,你肯定需要添加控制器。

+0

感謝這麼多,但究竟如何做呢? @property(nonatomic,retain)ViewController MyViewController?我是否通過#importing添加控制器? – 2011-05-30 12:30:07

+1

你已經在你的子類UIButton中創建了屬性。添加另一個(UIViewController * myViewController),在初始化Button之後,添加viewController([yourbutton setMyViewController:self];並用[self.myViewConroller yourMessage]在你的UIButton子類中調用它; – cem 2011-05-30 12:32:27

+0

非常感謝,但我沒有得到這個工作。我現在得到錯誤消息'訪問未知的viewController getter方法,當我調用[self.theViewController doSomething]; – 2011-05-30 13:03:43

2

使用非常簡單的代表 Objective-C的概念。

檢查我的答案在下面的帖子中使用Objective-C中的委託。

How do I set up a simple delegate to communicate between two view controllers?

+1

這是一種更清潔的方法,它不會將你的按鈕綁定到你的視圖控制器,您有機會稍後再使用它。 – 2011-05-30 12:36:55

+0

@Deepak:謝謝......但我很頭痛,想要理解這一點......這並不是我想要的那麼簡單。也許我需要更多時間來解決這個問題。就目前而言,我堅持使用未安裝的顯然是「不乾淨」的方法。 – 2011-05-30 13:27:29

+1

@ n.evermind:委託概念是在Objective-C編程中廣泛使用的東西,如果你花一些時間去理解它並在許多情況下對你有幫助,那將會更好。 – Jhaliya 2011-05-30 13:46:06

相關問題