IOS:在@selector中添加一个参数 [英] IOS: add a parameter to @selector
问题描述
当我有这行代码时
UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(dragGestureChanged:)];
此
- (void)dragGestureChanged:(UILongPressGestureRecognizer*)gesture{
...
}
我想在@selector(dragGestureChanged :)中添加一个参数(UIScrollView *)scrollView,我该怎么办?
I want to add at "@selector(dragGestureChanged:)" a parameter that is "(UIScrollView*)scrollView", how can I do?
推荐答案
你不能直接 - UIGestureRecognizer
知道如何调用只接受一个参数的选择器。要完全一般,你可能希望能够传递一个块。苹果公司还没有这样做,但它很容易添加,至少如果你愿意将手势识别器子类化,你想要解决添加新属性和正确清理的问题,而不深入研究运行时。
You can't directly — UIGestureRecognizer
s know how to issue a call to a selector that takes one argument only. To be entirely general you'd probably want to be able to pass in a block. Apple haven't built that in but it's fairly easy to add, at least if you're willing to subclass the gesture recognisers you want to get around the issue of adding a new property and cleaning up after it properly without delving deep into the runtime.
所以,例如(我去的时候写的,未经检查)
So, e.g. (written as I go, unchecked)
typedef void (^ recogniserBlock)(UIGestureRecognizer *recogniser);
@interface UILongPressGestureRecognizerWithBlock : UILongPressGestureRecognizer
@property (nonatomic, copy) recogniserBlock block;
- (id)initWithBlock:(recogniserBlock)block;
@end
@implementation UILongPressGestureRecognizerWithBlock
@synthesize block;
- (id)initWithBlock:(recogniserBlock)aBlock
{
self = [super initWithTarget:self action:@selector(dispatchBlock:)];
if(self)
{
self.block = aBlock;
}
return self;
}
- (void)dispatchBlock:(UIGestureRecognizer *)recogniser
{
block(recogniser);
}
- (void)dealloc
{
self.block = nil;
[super dealloc];
}
@end
然后你可以做:
UILongPressGestureRecognizer = [[UILongPressGestureRecognizerWithBlock alloc]
initWithBlock:^(UIGestureRecognizer *recogniser)
{
[someObject relevantSelectorWithRecogniser:recogniser
scrollView:relevantScrollView];
}];
这篇关于IOS:在@selector中添加一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!