The tag value is an Integer:
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:addressField forState:UIControlStateNormal];
[bu
NSLog(@"The part number is:%@",[NSString stringWithFormat:@"%d",(UIControl*)sender).tag]);
You can convert the integer value of a tag to a NSString with:
[NSString stringWithFormat:@"%i", ((UIControl*)sender).tag];
Or, if you really need a string as identifier for an UI object, just subclass it and add a property like:
@property (nonatomic, strong) NSString *stringID;
And then use it instead of use the tag property.
There is a simple way for passing a NSString parameter with uibutton i.e. just set title of buuton with clear color and font size 0.0f.This is valid if your using a image([button setBackgroundImage:anyImage. forState:UIControlStateNormal];) on button and not showing the titl and then you can get "sender.currentTitle" and use this variable
try
-(void)pickTheQuiz:(id)sender{
NSNumber *tag = [NSNumber numberWithInt:sender.tag];
NSLog(@"The part number is:%@",[tag stringValue]);
}
Probably not best practice, but one simple way to pass a string with UIButton
is to store it in the accessibilityIdentifier
property.
yourButton.accessibilityIdentifier = "Some string you want to pass"
...
@objc func tappedButton(sender: UIButton) {
print("passed string is: \(sender.accessibilityIdentifier)")
}
The tag property will only accept integers, and if hacking the integer value to get to a string is not an option for you, you can sub-class the UIButton, and then use the User Defined Runtime Attributes section in IB to set the value of the property in your StoryBoard.
Subclass the UIButton with a new non-integer property:
@interface MyCustomUIButton : UIButton @property (strong) NSString* stringTag; @end
Set your button's class to the sub-class:
Identity inspector > Custom Class > Class => MyCustomUIButton
Set the property value from IB OR through code:
From IB:
Identity inspector > User Defined Runtime Attributes:
Key Path => stringTag
Type => String
Value => yourstringvalue
OR From Code:
((MyCustomUIButton*)yourButton).stringTag = @"yourstringvalue";
Then you can retrieve the value of the property from your button action method:
-(void)yourMethod:(id)sender
{
NSLog(@"The string value is: ",((MyCustomUIButton*)sender).stringTag);
// or use this idiom, to avoid a possible crash if it's the wrong class:
if ( [sender respondsToSelector:@selector(stringTag)] )
testeee = [sender valueForKey:@"stringTag"];
else
NSLog(@"this IS NOT a MyCustomUIButton, it's a plain UIButton");
// testeee will be NULL if you FORGOT to set the
// User Defined Runtime Attribute for 'stringTag' in storyboard
// note that a useful alternative to
// if ( [sender respondsToSelector:@selector(stringTag)] )
// is...
// if ( [sender respondsToSelector:NSSelectorFromString(@"stringTag")] )
}