我想使用MutableArray计数创建多个按钮。创建按钮后,每当按下特定按钮,我想在标签中显示该按钮名称。但是一旦按下按钮,它总是显示MutableArray的最后一个索引值名称。请帮助解决这个问题。我是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的最后一个对象“Five”。我想要按下按钮当前标题。
答案 0 :(得分: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状态。
答案 1 :(得分:2)
试试这样:
-(void) clicks:(id)sender
{
if ([sender isKindOfClass:[UIButton class]])
{
UIButton *button = (UIButton*)sender;
NSString *title = button.currentTitle;
// do whatever you want with title
}
}
答案 2 :(得分:1)
尝试赞,
-(void)clicks:(id)sender{
UIButton *resultebutton= (UIButton*)sender;
label.text=resultebutton.titleLabel.text;
}