Iphone 如何在UIButton中实现addTarget属性
我有一个函数(例如function1),其中有一个按钮和一个名为auxiliarStruct的对象,我有一行:Iphone 如何在UIButton中实现addTarget属性,iphone,objective-c,ios,xcode,Iphone,Objective C,Ios,Xcode,我有一个函数(例如function1),其中有一个按钮和一个名为auxiliarStruct的对象,我有一行: [btn addTarget:self action:@selector(userSelected:) forControlEvents:UIControlEventTouchUpInside]; 但在@selector(userSelected)中,我需要将该函数所需的对象作为参数传递,但我不知道如何实现它。 我在这里声明了这个目标: //UsersController.h #im
[btn addTarget:self action:@selector(userSelected:) forControlEvents:UIControlEventTouchUpInside];
但在@selector(userSelected)中,我需要将该函数所需的对象作为参数传递,但我不知道如何实现它。
我在这里声明了这个目标:
//UsersController.h
#import <UIKit/UIKit.h>
@interface UsersController : NSObject{
NSInteger *prof_id;
NSString *createTime;
NSString *fullName;
NSString *thumb;
}
@property (nonatomic) NSInteger *prof_id;
@property (nonatomic, retain) IBOutlet NSString *createTime;
@property (nonatomic, retain) IBOutlet NSString *fullName;
@property (nonatomic, retain) IBOutlet NSString *thumb;
@end
我有一个这个类的对象,叫做auxiliarStruct,这就是我需要的。我试过了
[btn addTarget:self action:@selector(**userSelected:auxiliarStruct**)forControlEvents:UIControlEventTouchUpInside];
但它不起作用
有人能帮我吗?谢谢
ps:对不起我的英语,我知道它不好您只能通过addTarget@selector
方法将(UIButton*)
对象作为参数传递。您可以设置UIButton标记并在被调用的函数上使用它。您可能希望找到发送字符串值的任何替代方法
使用以下代码传递带有按钮的标记:
btn_.tag = 10;
[btn_ addTarget:self action:@selector(functionName:) forControlEvents:UIControlEventTouchUpInside];
按钮操作应如下所示:
- (void) functionName:(UIButton *) sender {
NSLog(@"Tag : %d", sender.tag);
}
事件将按钮作为参数发送,因此:
-(void)userSelected:(id)sender {
UIButton *button = sender;
...
}
我不知道是否可以为按钮的操作添加参数,我从未遇到过这样的方法 我们所做的最接近的事情是为按钮选择不同的标签,并根据标签区分动作 无论如何,这并不能完全回答您的问题,但我建议使用类属性代替发送参数。例如:
- 您单击按钮,希望将值“test”发送到选择器。您没有发送“test”,而是将该类属性设置为“test”,然后在选择器中读取它。我不知道它是否适合你的需要100%,但我认为这是一个选择。
显然,你不是唯一一个提出这个问题的人:在这种情况下,也没有标准的解决方案,使用了标签。什么样的参数?你能举个例子吗?一个自己类的对象,里面有4个nsstrings:UsersController:NSObject{NSInteger*prof_id;NSString*createTime;NSString*fullName;NSString*thumb;}Pfitz,我编辑了这个问题。我希望您现在能理解它,因此您得到了一个类
UserController
如何在声明按钮的目标操作方法的类中访问该类?不确定您是否理解我。我只想通过addTargetNeptune将变量作为参数传递给函数userSelected,我正在尝试使用标记。我有这样一个:btn.tag=(auxiliarStruct.prof_id);如何在userSelected函数中从auxiliarStruct.prof_id获取正确的值?。现在我有了这行代码:NSInteger*userid=((UIControl)sender).tag;但是NSLog没有显示正确的值我理解,但是我需要中的auxiliarStruct.prof_id的值tag@nanoDev请先记录auxiliarStruct.prof_id的值,然后再将其设置为按钮标记。auxiliarStruct.prof_id必须是整数。
-(void)userSelected:(id)sender {
UIButton *button = sender;
...
}