Objective c 如何将关联对象添加到UITap手势?
目前我的代码中有Objective c 如何将关联对象添加到UITap手势?,objective-c,ios,Objective C,Ios,目前我的代码中有 tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addCompoundToLabel:)]; 如果是这样的话,我的代码会更干净 tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addCompoundToLabel:) withObject:data]; 我了解到关联对象允许
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addCompoundToLabel:)];
如果是这样的话,我的代码会更干净
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addCompoundToLabel:) withObject:data];
我了解到关联对象允许您在手势识别器中传递对象,但在阅读文档后,我不太明白如何在代码中实现它。将欣赏关联对象的示例实现。谢谢
编辑:
这就是addcomposite
的开头
- (void)addCompoundToLabel:(UIGestureRecognizer *)recognizer {
if( [recognizer state] == UIGestureRecognizerStateEnded ) {
FormulaLabel* label = (FormulaLabel*)[recognizer view];
使用关联对象是一个混乱的解决方案。相反,您可以创建一个假目标对象,将您的
ui视图
和数据
赋予它,并通过选择器方法访问这两个对象。它更具可读性,并且您的代码更好地表达了您的意图
下面是一个简单的例子:
@interface FalseTarget : NSObject {
MyViewController *_viewCtrl;
MyData *_data;
}
-(id)initWithViewCtrl:(MyViewController*)viewCtrl andData:(MyData*)data;
-(void)tap:(id)sender;
@end
@implementation
-(id)initWithViewCtrl:(MyViewController*)viewCtrl andData:(MyData*)data {
self = [super init];
if (self) {
_viewCtrl = viewCtrl;
_data = data;
}
return self;
}
-(void)tap:(id)sender {
[_viewCtrl processTapFromSender:sender withData:_data];
}
@end
将processTapFromSender:withData:
方法添加到控制器:
-(void)processTapFromSender:(id)sender withData:(MyData*)data {
// Your action
}
现在,您可以创建如下所示的点击识别器:
FalseTarget *target = [[FalseTarget alloc] initWithViewCtrl:self andData:data];
tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:@selector(tap:)];
你为什么要这么做?您可以将UITapGestureRecognizer子类化并添加ivar成员有没有办法使
tap
方法位于视图控制器中?