2012-09-18 23 views
2

我在我的代碼中有以下IBAction方法。如何以編程方式使用ID發件人調用IBAction方法?

-(IBAction)handleSingleTap:(id)sender 
{ 
    // need to recognize the called object from here (sender) 
} 


UIView *viewRow = [[UIView alloc] initWithFrame:CGRectMake(20, y, 270, 60)]; 
// Add action event to viewRow 
UITapGestureRecognizer *singleFingerTap = 
[[UITapGestureRecognizer alloc] initWithTarget:self 
             action:@selector(handleSingleTap:)]; 
[self.view addGestureRecognizer:singleFingerTap]; 
[singleFingerTap release]; 
// 
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(5,30, 100, 20)]; 
infoLabel.text = @"AAAANNNNVVVVVVGGGGGG"; 
//[viewRow addSubview:infoLabel]; 
viewRow.backgroundColor = [UIColor whiteColor]; 

// display the seperator line 
UILabel *seperatorLablel = [[UILabel alloc] initWithFrame:CGRectMake(0,45, 270, 20)]; 
seperatorLablel.text = @" ___________________________"; 
[viewRow addSubview:seperatorLablel]; 
[scrollview addSubview:viewRow]; 

如何調用IBAction方法,同時允許它接收該方法的調用者對象?

回答

3

方法簽名對於手勢識別器和UIControls是通用的。兩者都會在沒有警告或錯誤的情況下工爲了確定發送者,首先要確定該類型...

- (IBAction)handleSingleTap:(id)sender 
{ 
// need to recognize the called object from here (sender) 
    if ([sender isKindOfClass:[UIGestureRecognizer self]]) { 
     // it's a gesture recognizer. we can cast it and use it like this 
     UITapGestureRecognizer *tapGR = (UITapGestureRecognizer *)sender; 
     NSLog(@"the sending view is %@", tapGR.view); 
    } else if ([sender isKindOfClass:[UIButton self]]) { 
     // it's a button 
     UIButton *button = (UIButton *)sender; 
     button.selected = YES; 
    } 
    // and so on ... 
} 

稱呼它,直接調用它,讓它連接到調用它,或讓手勢識別稱之爲UIControl。他們都會工作。

+0

感謝您的驚人提示。我設法得到該方法調用視圖的標籤。我在代碼中犯了一個錯誤,我已經將UITapGestureRecognizer分配給了self.view,而不是我想要分配的內容。 –

1

您不必調用它,因爲您使用的方法與UITapGestureRecognizer中的Selector一樣,所以在應用程序出現輕擊時它會自動調用。 另外,如果您可以在action:@selector(handleSingleTap:)中的方法名稱後識別冒號,則表示將UITapGestureRecognizer類型的對象發送給方法。如果您不想發送任何對象,則只需從該方法中刪除冒號和(id)sender

+0

我想他可能想從其他角度來調用它。 – Kjuly

+0

感謝您的提示 –

1

當你想:

[self handleSingleTap:self.view]; 

sender可以通過任何東西,只要你喜歡,它的id類型。你也可以用一個標籤發送一個UIButton實例。

相關問題