15

I have a UIButton in a Storyboard scene. The button has a User-Defined-RunTime-Attribute 'type'(String) configured. When pressed the button calls

-(IBAction)pressedButton:(id)sender

Will I be able to access the User-Defined-RunTime-Attribute from 'sender'?

Apurv
  • 17,116
  • 8
  • 51
  • 67
eric
  • 4,863
  • 11
  • 41
  • 55

1 Answers1

23

Yes:

-(IBAction)pressedButton:(id)sender
{
    id value = [sender valueForKey:key];
}

Note that you cannot use a User Defined Run Time attribute, unless you subclass UIButton and add it as a strong property, for example

@interface UINamedButton : UIButton
@property (strong) NSString *keyName;
@end

If you set a User Defined Run Time attribute, and you have not done this, Xcode will badly crash unfortunately.

You can then get that value like

-(IBAction)clicked:(UIControl *)sender
    {
    NSString *test = @"???";

    if ( [sender respondsToSelector:@selector(keyName)] )
            test = [sender valueForKey:@"keyName"];

    NSLog(@"the value of keyName is ... %@", test);

    // if you FORGOT TO SET the keyName value in storyboard, that will be NULL
    // if it's NOT a UINamedButton button, you'll get the "???"

    // and for example...
    [self performSegueWithIdentifier:@"idUber" sender:sender];
    // ...the prepareForSegue could then use that value in the button.

    // note that a useful alternative to
    // if ( [sender respondsToSelector:@selector(stringTag)] )
    // is... 
    // if ( [sender respondsToSelector:NSSelectorFromString(@"stringTag")] )
    }
Fattie
  • 27,874
  • 70
  • 431
  • 719
trojanfoe
  • 120,358
  • 21
  • 212
  • 242