如何从“发件人”对象访问用户定义的运行时属性?
在Storyboard场景中有一个UIButton
。 该button具有configuration的用户定义的运行时间属性“types”(string)。 当按下button调用
-(IBAction)pressedButton:(id)sender
我能够从“发件人”访问用户定义的运行时间属性吗?
是:
-(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")] ) }