Agamemnon
Agamemnon

Reputation: 607

Using programmatically created UIButtons with the same method to load different UIViewControllers

I have programmatically generated UIButtons that all share the same selector method. When the method runs I would like the method to know which button was pressed and then be able to load a corresponding UIViewController.

-(void)buildButtons
{
    for( int i = 0; i < 5; i++ ) {
    UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [aButton setTag:i];
    [aButton addTarget:self action:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];
    [aView addSubview:aButton];
}

Then:

- (void)buttonClicked:(UIButton*)button
{
    NSLog(@"Button %ld clicked.", (long int)[button tag]);
    // code here that picks the correct viewController to push to...
    // for example tag 1 would create an instance of vcTwo.m and would then be pushed to the navigationController and be displayed on screen
}

say I have three UIViewController classes (vcOne.m, vcTwo.m, vcThree.m) and I want it so that when the button is pressed 'buttonClicked' is run and the code picks the corresponding viewController to push to. I don't want to use a series of if statements as there may be dozens/hundreds of viewControllers in the end. Would I have to instantiate all of the viewControllers and put them in an array? Is there a better way?

Upvotes: 0

Views: 89

Answers (2)

Agamemnon
Agamemnon

Reputation: 607

In the end I went with this:

- (void) buttonClicked:(id)sender
{
    NSLog(@"Button tag = %li", (long)[sender tag]);
    FormularyVC *formularyVCInstance = [FormularyVC alloc];
    ProceduresVC *proceduresVCInstance = [ProceduresVC alloc];
    VetMedVC *vetMedVCInstance = [VetMedVC alloc];

    NSArray *vcArray = [NSArray arrayWithObjects:formularyVCInstance, proceduresVCInstance, vetMedVCInstance, nil];

    UIViewController *vcToLoad = [vcArray objectAtIndex:(int)[sender tag]];
    vcToLoad.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:vcToLoad animated:NO];

}

I created an array of the ViewControllers I wanted to be able to load based on which button was pressed. When the button is pressed the method is run and the tag is taken as a parameter. This tag is used to find the ViewController needed by checking its location on the array's index.

Upvotes: 0

Meeshoo
Meeshoo

Reputation: 141

Are you using storyboards? so you can chose a segue according to the button tag:

int i = (int)[button tag];
[self performSegueWithIdentifier:[NSString stringWithFormat:@"Segue%d", i] sender:self];

or:

UIViewController *viewController= [controller.storyboard instantiateViewControllerWithIdentifier:NSString stringWithFormat:@"ViewControllerNumber%d", i];

Upvotes: 1

Related Questions