我在Storyboard场景中有一个UIButton
。该按钮配置了User-Defined-RunTime-Attribute'type'(String)。按下按钮调用
-(IBAction)pressedButton:(id)sender
我是否可以从'sender'访问User-Defined-RunTime-Attribute?
答案 0 :(得分: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")] )
}