2012-05-16 63 views
3

我是一名新的iPad開發人員。如何識別Objective-C中哪個按鈕被點擊?

我已經創建了UIButton以編程方式,其中我想確定用戶已經點擊了哪個按鈕,並根據我想做的一些行動。

我該如何識別?

這裏是我的代碼片段:

for(int i=0;i<[_array count];i++) 
    { 

     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     button.tag=count; 
     [button addTarget:self 
        action:@selector(aMethod:) 
     forControlEvents:UIControlEventTouchDown]; 

     button.backgroundColor=[UIColor redColor]; 
     [button setTitle:@"Show View" forState:UIControlStateNormal]; 
     button.frame = CGRectMake(xpos, 270.0, 200.0, 150.0); 

     [self.view addSubview:button];    
    } 

這是我現在在做什麼:我以爲我會分配計數給各按鈕,我會把這個計數按鈕點擊方法。這是一個好主意嗎?有沒有其他方法可行?

在按鈕點擊我打電話aMethod

-(void)aMethod:(id)sender{ 
    NSLog(@"btn clicked"); 

} 

任何幫助將不勝感激!

+0

你的邏輯和想法沒有錯。您可以訪問按鈕中的「標籤」來區分對方。是的,我可以說,這是個好主意。我在我的項目中也這樣做了。 – HelmiB

回答

16
-(void)aMethod:(UIButton*)sender{ 
    NSLog(@"btn clicked %d", sender.tag); 

} 
+1

是的,您可以使用按鈕的標籤來標識哪個按鈕已被按下。 – ilight

+0

這是我會這樣做的方式。我相信使用標籤屬性是識別按鈕的標準方式。 – geminiCoder

相關問題