在iOS中创建带参数的UIButton操作
我有一个名为firstButton的在iOS中创建带参数的UIButton操作,ios,Ios,我有一个名为firstButton的UIBUtton,下面有一行用于添加目标。但是,我得到了一个错误: 分析问题(预期) 正确的语法是什么 [firstButton addTarget:self action:@selector(responseAction: 1) forControlEvents:UIControlEventTouchUpInside]; - (IBAction) responseAction:(int)buttonPressed { NSLog(@"%d&quo
UIBUtton
,下面有一行用于添加目标。但是,我得到了一个错误:
分析问题(预期)
正确的语法是什么
[firstButton addTarget:self action:@selector(responseAction: 1) forControlEvents:UIControlEventTouchUpInside];
- (IBAction) responseAction:(int)buttonPressed
{
NSLog(@"%d", buttonPressed);
}
你不应该这样争论。如果需要,可以使用标记 所谓的“iActions”必须具有以下签名之一:
-(void)action;
-(void)actionWithSender:(id)sender;
-(void)actionWithSender:(id)sender event:(UIEvent*)event;
不能添加任何其他参数。但是,您可以使用发送者(在您的情况下是按钮1或按钮2)来获取参数:
-(void)actionWithSender:(UIButton*)sender {
NSString* parameter;
if (sender.tag == 1) // button1
parameter = @"foo";
else // button2
parameter = @"bar";
...
}
以上答案来自此链接->
希望有帮助。使用objective-c类别和关联可以帮助添加几乎任何类型的参数:
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);
OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);
如何使用:
UIButton+UserInfo.h:
@interface UIButton (UserInfo)
@property (nonatomic, retain) id userInfo;
@end
UIButton+UserInfo.m:
@implementation UIAlertView (UserInfo)
static char ContextPrivateKey;
- (void)setUserInfo:(id)userInfo
{
objc_setAssociatedObject(self, &ContextPrivateKey, userInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (id)userInfo
{
return objc_getAssociatedObject(self, &ContextPrivateKey);
}
@end
在代码中应用:
#import "UIButton+UserInfo.h"
[firstButton addTarget:self action:@selector(responseAction: 1) forControlEvents:UIControlEventTouchUpInside];
firstButton.userinfo = /*your argument*/;
- (IBAction) responseAction:(int)buttonPressed
{
NSLog(@"%@", firstButton.userinfo );
}
希望能帮助您。复制: