UIButton IBAction button name
I wish to know the name of the button that was just tapped. I have this code so far:
开发者_StackOverflow- (IBAction)buttonClick:(id)sender{
NSLog(@"%@",sender);
}
However, this just returns a lot of jargon. Is there a way to return the name of the button that was just tapped?
If you want to know the name just so you know what button has been clicked, I don't think you can get the name of the iVar, but there are other ways of doing this:
You can get the title of the button:
NSString *btnTitle = [sender currentTitle];
Alternatively - You can set a tag for the button in the Interface Builder view
NSInteger btnTag = [sender tag];
You could use the Objective-C runtime functions but this might be difficult.
What I recommend instead is setting the tag
property for each button, and create an array with the names of each button, like this:
button1.tag = 0;
button2.tag = 1;
NSArray *buttonNames = [NSArray arrayWithObjects:@"button1", @"button2", nil];
In your method:
- (IBAction)buttonTap:(id)sender { // one cannot *click* on an iOS device
NSLog(@"%@", [buttonNames objectAtIndex:[(UIButton *)sender tag]);
}
try
NSLog(@"%@",[sender title]);
精彩评论