I create a button and set title as \"Click here\". When I press that button I want to get that button title and log it. Here\'s my code, where am I going wrong?
-(void)clicketbutton {
UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeCustom];
[mybutton setTitle:@"Click here" forState:UIControlStateNormal];
[mybutton addTarget:self
action:@selector(displayvalue:)forControlEvents:UIControlEventTouchUpInside];
}
-(void)displayvalue:(id)sender {
NSLog(@"The title is %@ ", [mybutton titleForState:UIControlStateNormal]);
}
Your displayvalue: method should look something like this:
-(void)displayvalue:(id)sender {
UIButton *resultButton = (UIButton *)sender;
NSLog(@" The button's title is %@.", resultButton.currentTitle);
}
(Please check out the documentation in XCode, it would have given you the right answer.)
I know it's a bit of an old question, but this is probably the neatest way to resolve this one.
NSLog(@"The button title is: %@", [sender currentTitle]);
Edit
I've just realised that this is depending on the fact that you have set the receiving parameter to UIButton*
. Rather than using the default id
, creating a UIButton
object and casting (id)sender
to that button. Cut out the middle man and just set the function signature to
-(void)buttonPressed:(UIButton*)sender{
NSLog(@"Button title: %@",sender.currentTitle);
}
This is effectively casting the function parameter
-(void)displayvalue:(id)sender
{
UIButton *resultebutton= (UIButton*)sender;
NSLog(@"The button title is %@ ", resultebutton.titleLabel.text);
}