Reputation: 5
So, be warned, I'm an absolute beginner. In XCode, is it possible to refer to the name of the button in the action? So I want to use an if statement to check if the name of the button (which I also use as the name of the image behind the button) is in an array that has already been created. I've created the button in the storyboard, linked it to the .h file like:
- (IBAction)s11:(id)sender;
and all I've got in the .m file so far (relating to the button) is:
- (IBAction)s11:(id)sender {
if ( )
}
Upvotes: 0
Views: 148
Reputation: 1623
Since you need to check the name of the button use this:
- (IBAction)s11:(id)sender {
UIButton *btn = (UIButton *)sender;
if ([btn.titleLabel.text isEqualToString:@"BUTTON_NAME"]){
// do your stuff
}
}
Upvotes: 1
Reputation: 14687
If you want to reference the button globally in your implementation file you have 2 options:
Option A: Create an IBOutlet for the Button and use the assigned outlet pointer name. Option B: Give your UIButton a unique tag, then access it via it's tag, using this:
UIButton *myButton = (UIButton*)[self.view viewWithTag:255];
The tag number here is 255, but you should use your own.
Upvotes: 0
Reputation: 1281
Try it....
You could assign a "tag" attribute for every button
- (IBAction)s11:(id)sender
{
int i = [sender tag];
NSLog(@"Button tag : %i",i);
if (i == 0)
{
NSLog(@"btn 1 clk");
}
if (i == 1)
{
NSLog(@"btn 2 clk");
}
}
Hope i helped.
Upvotes: 0
Reputation: 4953
- (IBAction)s11:(id)sender {
UIButton *btn=sender;
if ([yourArray containsObject:[btn titleForState:UIControlStateNormal]]) {
}
Upvotes: 0
Reputation: 8512
You can use titleForState:
or maybe currentTitle
method. Since the current title can change depending on button state, I recommend titleForState:
.
- (IBAction)s11:(UIButton *)button {
NSString *title = [button titleForState:UIControlStateNormal];
if ([self.theArray containsObject:title]) {
// code
}
}
This is not the best way to distinguish between buttons, but you asked for it. Better would be to have those buttons in array.
Upvotes: 0
Reputation: 4254
You could assign a "tag" attribute for every button (attributes inspector) and check for that in your code
- (IBAction)s11:(id)sender {
switch(sender.tag) {
case 1: {
...
}
case 2: {
...
}
...
}
}
Upvotes: 0
Reputation: 14160
sender is the pointer to button you clicked. So you can cast it to UIButton and do whatever you need - check it's title, tag, whatever else.
Upvotes: 1