2012-07-09 16 views
2

我是iOS的初學者,並且在編程教程中以編程方式添加按鈕時,target始終設置爲self,並且在該控制器中正在創建它的位置,將執行一個操作(IBAction)。或者通過界面生成器,目標被設置爲文件的所有者。當按鈕(UIButton)的目標不是「自我」時?

我的問題是,在什麼情況下(一個例子會很棒),目標不是自我。

一種情況我能想到的是,當在一個類的(這不是一個ViewController)方法一個按鈕被根據條件創建的,因爲這類不是一個ViewController,初始化該類的一個對象時,參考到當前的ViewController將被設置,並且將被用作目標,如果該按鈕出現,則爲該按鈕定義動作。

回答

6

您可以直接選擇到任何目標 - 之所以通常,self是目標,因爲這是很正常的代碼實例化一個的UIButton /的UIBarButtonItem,所以很多教程包括實現在選擇參考資料同班。

你可以,例如,使一個類,在您的視圖控制器實例化時,僅設計爲處理這些按鈕調用操作:

#import <UIKit/UIKit.h> 
#import "OtherObject.h" 

@interface SomeViewController : UIViewController 

@property (strong, nonatomic) OtherObject *other; 

@end 

@implementation SomeViewController 

@synthesize other; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    UIButton *someButton = [[UIButton alloc] initWithFrame:CGRectZero]; 
    [someButton addTarget:other action:@selector(someMethodInOther) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:someButton]; 

    UIButton *anotherButton = [[UIButton alloc] initWithFrame:CGRectZero]; 
    [anotherButton addTarget:other action:@selector(anotherMethodInOther) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:anotherButton]; 
} 

@end 

IBAction爲可讓您在Interface Builder中這個方法的實現可以連接通過你的xib/storyboard。

+0

謝謝!!!!!!!!!! – SpeedBirdNine 2012-07-09 12:22:52

相關問題