如何添加关联对象来点击手势?

时间:2012-02-11 03:50:06

标签: objective-c ios

目前我的代码

tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addCompoundToLabel:)];

如果类似

,我的代码会更干净
tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addCompoundToLabel:) withObject:data];

我读到关联对象允许您在手势识别器中传递对象,但在阅读文档后,我不太明白如何将其实现到我的代码中。将理解关联对象的示例实现。感谢

编辑:

这是addCompound的开头

- (void)addCompoundToLabel:(UIGestureRecognizer *)recognizer {

 if( [recognizer state] == UIGestureRecognizerStateEnded ) {

      FormulaLabel* label = (FormulaLabel*)[recognizer view];  

1 个答案:

答案 0 :(得分:1)

使用关联对象是一个混乱的解决方案。相反,您可以创建一个错误的目标对象,为其指定UIViewData,并在选择器方法中访问这两个对象。它更具可读性,您的代码表达了您的意图更好。

这是一个快速而又肮脏的例子:

@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:)];