Search code examples
iphoneobjective-cuibuttonios6.1

How to create Multiple buttons programmatically, get button name whenever press on particular button?


I want to create multiple buttons using MutableArray count. After creating the button, whenever pressing on particular button, I want to display that button name in a label. But Once press on button, it is always showing the MutableArray last index value name. Please help in this problem. I am fresher ti iOS. It's my code.

-(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
}

But, here button current title is always showing MutableArray last object "Five" only. I want pressed button current title.


Solution

  • -(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
    }
    

    Try this code. I using following method to get title of button

    titleForState:

    Returns the title associated with the specified state. - (NSString *)titleForState:(UIControlState)state Parameters

    state

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

    Return Value

    The title for the specified state. If no title has been set for the specific state, this method returns the title associated with the UIControlStateNormal state.

    Read Documentation https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/occ/instm/UIButton/titleForState: