How to access User Defined Runtime Attribute from

2019-07-20 07:50发布

我有一个UIButton在故事板的场景。 按钮具有一个用户定义的运行时属性“类型”(字符串)构成。 当按下按钮呼叫

-(IBAction)pressedButton:(id)sender

我将能够访问来自“发件人”用户自定义运行时属性?

Answer 1:

是:

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

请注意,您不能使用已定义的运行时间属性的用户, 除非你继承的UIButton并将其添加为一个强大的特性 ,例如

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

如果设置定义运行时属性的用户,你还没有这样做时,Xcode将严重崩溃不幸。

那么你可以得到这样的价值

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


文章来源: How to access User Defined Runtime Attribute from the 'sender' object?