2011-05-23 10 views
0

我已經創建了動態的按鈕。現在我想獲得按鈕索引值。如何獲得iPhone中的按鈕索引值?

這裏我的代碼, 對於例如, 我的數組,

{ 
    one, 
    two, 
    three, 
    Four 
} 

int x = 10; 

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

UIButton *answerBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

[answerBtn setFrame:CGRectMake(30, x, 260, 40)]; 

answerBtn.tag = i; 

[answerBtn setTitle:[answerList objectAtIndex:i] forState:UIControlStateNormal]; 

NSString *actualString = @"two"; 

NSString *getString = [answerList objectAtIndex:i]; 

if([actualString isEqualToString:getString]) 
{ 

    //How do i get the correct values of array index, In this case i want to return the index value is 1. Bcoz the array[1] = two. 
    NSLog(@"The btn tag is %d", answerBtn.tag); // couldn't get correct index 
} 

[self.view addSubview: answerBtn]; 
} 

預期的結果是,

The btn tag is 1. 
+1

你真的設置了標籤嗎? – 2011-05-23 14:28:39

+0

@Richard J Ross,是的,我編輯了我的問題,請現在看問題。 – Pugal 2011-05-23 14:30:50

+0

@Pugal我看不到你試圖從哪個按鈕獲取標籤。 'answerBtn'的標籤總是等於'i'。 – 2011-05-23 14:33:24

回答

1
NSLog(@"The btn tag is %d", answerBtn.tag); 
+0

+1 ...速度... – 2011-05-23 14:33:46

+0

這段代碼雖然完成了什麼? 'answerBtn'的標籤總是等於i。 – 2011-05-23 14:34:48

+0

這個問題不難回答:) – klefevre 2011-05-23 14:35:24

0

所有你需要設置按鈕標記獲取的第一它。

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

UIButton *answerBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

answerBtn.tag = i; 

[answerBtn setFrame:CGRectMake(30, x, 260, 40)]; 

[answerBtn setTitle:[answerList objectAtIndex:i] forState:UIControlStateNormal]; 

NSString *actualString = @"two"; 

NSString *getString = [answerList objectAtIndex:i]; 

if([actualString isEqualToString:getString]) 
{ 
    //How do i get the correct button index, In this case i want to return the tag is 1. 
    NSLog(@"The btn tag is %d", answerBtn.tag); // it's not w 
} 



[self.view addSubview: answerBtn]; 
} 
+2

這段代碼雖然完成了什麼? 'answerBtn'的標籤總是等於i。 – 2011-05-23 14:34:23

+0

你按鈕將有標籤的0,1,2,...,n-1,並且你可以從你的視圖中得到你的按鈕UIButton * currentButton =(UIButton *)[self.view viewWithTag:0];然後你可以做任何你想要的按鈕。 – 2011-05-25 06:11:57

相關問題