How to pass a string as a tag of UIButton

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

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

    #import 
    
    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);
    }
    

提交回复
热议问题