目前我的代码
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];
答案 0 :(得分:1)
使用关联对象是一个混乱的解决方案。相反,您可以创建一个错误的目标对象,为其指定UIView
和Data
,并在选择器方法中访问这两个对象。它更具可读性,您的代码表达了您的意图更好。
这是一个快速而又肮脏的例子:
@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:)];