xcode 如何从“发送者”对象访问用户定义的运行时属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15007542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:49:50  来源:igfitidea点击:

How to access User Defined Runtime Attribute from the 'sender' object?

iosobjective-cxcodeinterface-builder

提问by eric

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

我有一个UIButton故事板场景。该按钮配置了 User-Defined-RunTime-Attribute 'type'(String)。当按下按钮调用

-(IBAction)pressedButton:(id)sender

-(IBAction)pressedButton:(id)sender

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

我能否从“发送者”访问用户定义的运行时属性?

回答by trojanfoe

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

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

@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.

如果你设置了一个用户定义的运行时间属性,而你没有这样做,不幸的是 Xcode 会严重崩溃。

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