如何在iPhone中获取按钮索引值?

时间:2011-05-23 14:26:43

标签: iphone uibutton indexing

我已经动态创建了按钮。现在我想获得按钮索引值。

我的代码是, 对于Eg, 我的阵列,

 {
    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.

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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];
}