2011-03-17 149 views
0

我試圖編寫一個方便的方法,返回一個UIButton並將標題,CGRect和一個操作作爲參數。我的代碼編譯並運行,但當我實際單擊按鈕時崩潰。問題傳遞方法作爲參數

這裏是我的簡便方法:

+ (UIButton *)makeButton:(NSString *)title withRect:(CGRect)rect 
     withAction:(SEL)selectorX { 

    // setup button properties 
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    btn.frame = rect; 
    [btn setFont:[UIFont boldSystemFontOfSize:20]]; 
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; 
    btn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
    [btn setBackgroundImage:[[UIImage imageNamed:@"btn_21.png"] 
     stretchableImageWithLeftCapWidth:10.0                      
     topCapHeight:0.0] forState:UIControlStateNormal]; 
    [btn setTitle:@"TEST" forState:UIControlStateNormal]; 
    [btn addTarget:self action:@selector(selectorX:) 
     forControlEvents:UIControlEventTouchUpInside]; 

    return btn; 
} 

這裏是我怎樣,我稱之爲:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    btn = [Utilities makeButton:@"TEST" withRect:CGRectMake(10, 100, 236, 45) 
      withAction:@selector(buttonActionTEST:)]; 
    [self.view addSubview:btn]; 
} 

- (void) buttonActionTEST:(id)sender { 

    [Utilities alert:@"yo yo yeoman"]; 

} 

回答

1

您需要同時提供目標選擇器以調用該目標。你只是提供了選擇,然後做到這一點:

[btn addTarget:self action:@selector(selectorX:) 
    forControlEvents:UIControlEventTouchUpInside]; 

這是不對的兩個帳戶:第一,在這種情況下計算的類Utilities(甚至不是一個實例,但Class對象) 。然後,當您傳遞硬編碼選擇器selectorX:而不是具有幾乎相同名稱的變量時,嘗試提供選擇器也是錯誤的。它應該做的事是這樣的:

+ (UIButton *)makeButton:(NSString *)title withRect:(CGRect)rect 
     target:(id)aTarget action:(SEL)anAction { 
... 
    [btn addTarget:aTarget action:anAction 
     forControlEvents:UIControlEventTouchUpInside]; 
... 
} 

然後調用它像這樣:

btn = [Utilities makeButton:@"TEST" withRect:CGRectMake(10, 100, 236, 45) 
     target:self action:@selector(buttonActionTEST:)]; 
0

你方便的方法已經採取選擇作爲一個參數 - 這是一個真正的選擇器,所以靠近該方法的底部使用:

[btn addTarget:self action:selectorX forControlEvents:UIControlEventTouchUpInside]; 

(無需將selectorX包裝在@selector()中,因爲它選擇器)。

0

我認爲這個問題是從線來:

[btn addTarget:self action:@selector(selectorX:)  forControlEvents:UIControlEventTouchUpInside]; 

不會「自我「有公用事業類嗎?另外我不認爲你需要@選擇器。