Problem in Multiple button onclick event in iPhone
I have created five buttons in a for loop dynamically. Now I want to associate an OnClick event with every button which do different actions. How I can do this and how can I detect which button is clicked?
for (NSUInteger i=0;i<5;i++)
{
UIButton *myButton1 = [[UIButton buttonWithType:UIButtonTypeCustom]
in开发者_StackOverflow社区itWithFrame:CGRectMake(5, 57,15, 15)];
[myButton1 setTitle:@"Click Me!" forState:UIControlStateNormal];
[myButton1 addTarget:self action:@selector(buttonClicked1:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myButton1];
}
You could asseble the selector name into a string and turn the string into a selector:
for (int i=0; i<5; i++)
{
NSString *actionName = [NSString stringWithFormat:@"buttonClicked%i", i];
SEL action = NSSelectorFromString(actionName);
// …
}
But as the buttons will probably do something similar, it would be better if they all called the same method, where you would simply tell the buttons apart by the tag
:
for (int i=0; i<5; i++)
{
// …
[button setTag:i];
[button addTarget:self action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
}
- (void) buttonClicked: (id) button
{
const int tag = [button tag];
switch (tag) { /* … */ }
}
By the way, why do so many people insist on writing NSInteger
when you can simply type int
? Is there a difference? No that I know of.
Why are you creating 5 buttons in a for loop? Is there any particular reason why you're not using Interface Builder?
Also, the code you posted will place each button at the same position. A button will be on top of the previous button, and so on.
精彩评论