0

我想使用 MutableArray 计数创建多个按钮。创建按钮后,每当按下特定按钮时,我想在标签中显示该按钮名称。但是一旦按下按钮,它总是显示 MutableArray 最后一个索引值名称。请帮助解决这个问题。我更新鲜 ti iOS。这是我的代码。

-(void)ViewDidLoad {
    NSMutableArray *Mute_array=[[NSMutableArray alloc]initWithObjects:@"One", @"Two", @"Three", @"Four", @"Five", nil]; 

   for (int k=0; k<[Mute_array count]; k++){
       UIButton *btn_sub_category = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn_sub_category addTarget:self action:@selector(clicks:) forControlEvents:UIControlEventTouchDown];
        [btn_sub_category setTitle:[Mute_Sub_Category objectAtIndex:k] forState:UIControlStateNormal];
        btn_sub_category.frame = CGRectMake(278, k*130, 483, 44);
        [self.view addSubview:btn_sub_category];
    }
}

-(void)clicks:(id)sender{
   label.text=[btn_sub_category  currentTitle];       
   //Here a want to send the name of that clicked button current title
}

但是,此处按钮当前标题始终仅显示 MutableArray 最后一个对象“五”。我想按下按钮当前标题。

4

3 回答 3

2
-(void)clicks:(id)sender{
    UIButton *theButton = (UIButton*)sender;
    NSString *theButtonTitle = [theButton titleForState:UIControlStateNormal]
    NSLog(@"theButtonTitle :- %@", theButtonTitle);
    label.text=theButtonTitle;       
   //Here a want to send the name of that clicked button current title
}

试试这个代码。我使用以下方法获取按钮的标题

titleForState:

返回与指定状态关联的标题。- (NSString *)titleForState:(UIControlState)state 参数

状态

The state that uses the title. The possible values are described in UIControlState.

返回值

指定状态的标题。如果没有为特定状态设置标题,则此方法返回与 UIControlStateNormal 状态关联的标题。

阅读文档https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/occ/instm/UIButton/titleForState

于 2013-10-07T07:10:57.263 回答
2

试试这样:

-(void) clicks:(id)sender
    {
        if ([sender isKindOfClass:[UIButton class]])
        {
            UIButton *button = (UIButton*)sender;
            NSString *title = button.currentTitle;

            // do whatever you want with title
        }
    }
于 2013-10-07T07:20:34.017 回答
1

试试喜欢,

-(void)clicks:(id)sender{
 UIButton *resultebutton= (UIButton*)sender;
   label.text=resultebutton.titleLabel.text; 
}
于 2013-10-07T07:11:00.997 回答