How to pass a string as a tag of UIButton

前端 未结 8 1224
刺人心
刺人心 2020-12-16 02:41

The tag value is an Integer:

UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:addressField forState:UIControlStateNormal];
[bu         


        
8条回答
  •  鱼传尺愫
    2020-12-16 03:13

    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")] )
        }
    

提交回复
热议问题