How to pass a string as a tag of UIButton

前端 未结 8 1206
刺人心
刺人心 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

    as far as i know tags are always type int.

    youll need to convert it manually like:

    NSString *temp : [[NSString alloc]init];
    if(sender.tag == x){
        temp = @"some string";
    )
    

    and make cases for the different tags.

    please correct me if im wrong here :)

    0 讨论(0)
  • 2020-12-16 03:14

    You can do that as bellow with the help of feature objc_runtime

    #import <objc/runtime.h>
    
    static char kButtonAssociatedKey;
    
    NSString *aStrKey = [NSString stringWithFormat:@"Any Key"];
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:addressField forState:UIControlStateNormal];
    [button addTarget:self action:@selector(pickTheQuiz:) forControlEvents:UIControlEventTouchUpInside];
    button.tag=1;
    
    objc_setAssociatedObject(button,
                             &kButtonAssociatedKey,
                             aStrKey,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    -(void)pickTheQuiz:(id)sender
    {
        NSString *aStrKey = objc_getAssociatedObject(sender, &kButtonAssociatedKey);
        objc_removeAssociatedObjects(sender);
        NSLog(@"%@", aStrKey);
    }
    
    0 讨论(0)
提交回复
热议问题