2011-10-30 35 views
4

我要完成感人一個UIButton並具有比所有者不同類代碼運行。的UIButton設置觸摸處理程序代碼

我知道我可以做一個touchUpInside到該按鈕的所有者ClassA),然後調用內部ClassB,我想調用的方法,但有什麼辦法加快這個?

想法:

  • ClassB是爲ClassA->UIButton

  • 委託在編程的touchUpInside調用中使用的函數內部ClassB

我不知道如何完成其中任何一個我deas :(輸入是mas讚賞!

回答

17

一個選項是設置按鈕彈起使用

[myButton addTarget:yourOtherClass action:@selector(mySelector:) forControlEvents:UIControlEventTouchUpInside]; 

但這是有點危險的,因爲target不被保留,所以你可以發送郵件給解分配的對象。

您可以改爲建立一個協議

MyController.h 

@protocol MyControllerDelegate 
- (void)myController:(MyController *)controller buttonTapped:(UIButton *)button; 
@end 

@interface MyController : UIViewController 

@property (nonatomic, assign) id <MyControllerDelegate> delegate; 

- (IBAction)buttonTapped:(UIButton *)button; 

@end 

然後在你執行

MyController.m 

- (IBAction)buttonTapped:(UIButton *)button 
{ 
    if ([self.delegate respondsToSelector:@selector(myController:buttonTapped:)]) { 
     [self.delegate myController:self buttonTapped:button]; 
    } 
} 

在協議中定義的方法不是可有可無的,我可以代替做了(self.delegate)檢查,以使確定它被設置而不是respondsToSelector

+1

我使用了第一件事,因爲我從不關閉應用程序中的「目標」。不過,我非常感謝你給出反對的理由,因爲我的應用可能會發生變化。 – Jacksonkr