本文介绍了如何从'sender'对象访问用户定义的运行时属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Storyboard场景中有一个 UIButton
。该按钮配置了User-Defined-RunTime-Attribute'type'(String)。当按下按钮调用
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
我是否可以从'sender'访问User-Defined-RunTime-Attribute?
Will I be able to access the User-Defined-RunTime-Attribute from 'sender'?
推荐答案
是:
-(IBAction)pressedButton:(id)sender
{
id value = [sender valueForKey:key];
}
请注意,您不能使用用户定义的运行时属性,除非您将UIButton子类化并将其添加为强属性,例如
@interface UINamedButton : UIButton
@property (strong) NSString *keyName;
@end
如果您设置了用户定义的运行时间属性,但尚未完成不幸的是,Xcode会严重崩溃。
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")] )
}
这篇关于如何从'sender'对象访问用户定义的运行时属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!