14

我有UIButton一个故事板场景。该按钮配置了用户定义的运行时间属性“类型”(字符串)。按下按钮时调用

-(IBAction)pressedButton:(id)sender

我可以从“发件人”访问用户定义的运行时间属性吗?

4

1 回答 1

22

是的:

-(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")] )
    }
于 2013-02-21T16:39:39.637 回答