jamil
jamil

Reputation: 2437

NSMutableArray UIButtons Action?

I am Creating UIButtons programmatically and Then Store these UIButtons in NSMutableArray. All these UIButtons have Some Text as Titles. I have No Outlet for These UIButtons. Now I want to Assign the Title of UIButton to UIlabel when I touch or Click some UIButton. But the problem for me is this: how can I perform the function on these UIButtons. Because I created UIButtons programmatically and also these UIButtons have No Outlet. Here is my code to create Buttons:

     saveBtn = [[NSMutableArray alloc] init];

    for (int i=0; i<30; i++) {


        if (btnn>8) {
             UIButton *btn = [UIButton   
            buttonWithType:UIButtonTypeRoundedRect];
            btn.frame = CGRectMake(200.0 , spacey, 30.0, 30.0);
            int idx;
            idx = arc4random()%[arr count];
            NSString* titre1 = [arr objectAtIndex:idx];
            [btn setTitle:titre1 forState:UIControlStateNormal];      
            spacey=spacey+30;
            spacex = 80;
            btnn = 0;
            }
        else {
            btnn++ ;
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            btn.frame = CGRectMake(spacex, spacey, 30.0, 30.0);
            int idx;
            idx = arc4random()%[arr count];
            NSString* titre1 = [arr objectAtIndex:idx];
            [btn setTitle:titre1 forState:UIControlStateNormal];   
            spacex = spacex + 30;
            [saveBtn addObject:btn];
            [self.view addSubview:btn];

        }
    }

Please any one can guide me how can perfom action for these NSMutableArray UIButtons.

Upvotes: 0

Views: 908

Answers (3)

JainAnk
JainAnk

Reputation: 204

Create the action for the UIButton action, where you will be sending the (id)sender to the actionButtonFunction.

Assign sender to UIButton and then take the button title in NSString.

-(UIAction)buttonAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSString *buttonTitle = button.text;

    // further code goes here
}

Upvotes: 1

Tarun
Tarun

Reputation: 766

Simply set tag and add target to the button. Later, you can get which button was tapped.

Upvotes: 1

user529758
user529758

Reputation:

You can add actions to an UIButton programmatically using:

[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

- (void)buttonClicked:(UIButton *)btn
{
    [btn setTitle:@"UnAutreTitre" forState:UIControlStateNormal];
}

Hope this helps.

Upvotes: 2

Related Questions