My knowledge of Xcode and Obj-C is almost inexistant so please be understanding if I pose a stupid/badly formulated question.
I have added a series of buttons in the interface builder.
Now I want to link those buttons to a function (let’s say change a label’s text)
But each button should be able to change the text differently by sending a parameter of some sort.
-(IBAction)changeText:(NSString *) theString{
myLabel.text=theString;
}
When I add an action to a button I use something like this.
[but1 addTarget:self action:@selector(changeText : myString[1])
forControlEvents:UIControlEventTouchUpInside];
for the second button:
[but2 addTarget:self action:@selector(changeText : myString[2])
forControlEvents:UIControlEventTouchUpInside];
ans so on..
My question is:
If I have a large number of buttons, can I declare them in a loop and add the apropriate action to them at the same time? How do I do that?
The format for methods called by buttons is fixed. You can’t pass an arbitrary parameter, like a string, you can only pass either nothing, or the button itself.
This code won’t compile:
Because the myString[1] part makes your selector invalid. Selectors are just method names, you can’t put parameters inside them. The button decides what parameters to pass when it calls the method, and it always passes itself. You have two choices, you could give each button its own method, like this:
Note the lack of colon at the end of the changeText methods because we aren’t using the button parameter. You would then define your methods as:
But that’s not very scalable. An alternative approach would be to use some property of the button, such as it’s title or tag to branch the code. I think tag would work well for your purposes:
Note there is a colon at the end of the changeText: selector now. That means we want the button to pass itself as a parameter when it calls our method. The changeText method will now look like this: