Search code examples
iphoneobjective-ccocoa-touch

Objective-C - Passing Multiple Parameters


So up until now i would just pass any parameter i need via the buttons tag. However now i am using the tag already for something else so i need to be able to pass another string and a timer value with the tag to a void or action of some kind when you select the button.

This is my current button code for passing the buttons tag with to the action (below)

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

This is the void or action i am passing it to.

-(void)action:(UIButton*)btn{
NSLog(@"%d", [btn tag]);
}

So is there a way i can pass more than just the buttons tag (like a string) to the action? so i could have something like this.

-(void)action:(UIButton*)btn :myString{
NSLog(@"%d %@", [btn tag], myString);
}

Edit: So now thanks to the suggestion my void looks like this

-(void)actionWithButton:(UIButton *)btn andString:(NSString *)myString{
NSLog(@"%d %@", [btn tag], myString);
}

But i still don't know how to pass the myString parameter in the @selector part of the button.


Solution

  • You can add an UILable as a subView to that Button like

     UILabel *lblValue = [[UILabel alloc]initWithFrame:CGRectMake(0,0,0,0)];
     lblValue.tag=2;
     lblValue.text = myString;
     [objInputButton addSubview:lblValue];
    

    and you get your string in your Action method like below

      -(void)action:(UIButton*)btn
         {
         for(UILabel *lable in [btn subViews])
             {
                  if([lable tag]==2)
                       {
                             //get your string from lable
                       }
             }
         }
    

    Edit:- This answer by me is posted when I am starting my career, it is bad way of passing data even though it get works done, so, it is better to follow other answer posted by me.