IOS: 给@selector添加一个参数

8
当我有这行代码时
UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(dragGestureChanged:)];

并且这个

- (void)dragGestureChanged:(UILongPressGestureRecognizer*)gesture{
...
}

我想在"@selector(dragGestureChanged:)"中添加一个参数"(UIScrollView*)scrollView",应该怎么做?

2个回答

9
您不能直接这样做——UIGestureRecognizer只能调用一个带有一个参数的选择器。要完全通用,您可能想要能够传递一个块。苹果没有内置这个功能,但是如果您愿意对要绕过添加新属性和正确清理它而不深入运行时的手势识别器进行子类化,那么这将相当容易实现。
例如(边写边检查):
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];
        }];

我在哪里定义someObject,以及如何使用someObject - jerik
哥们,你是个超级巨星!喜欢这个答案...谢谢! - Tommie C.

3
所以这个方法将会是这样的:
- (void)dragGestureChanged:(UILongPressGestureRecognizer*)gesture
    scrollView:(UIScrollView *)scrollview
{
    ...
}

选择器将会长成这样:
UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc]
    initWithTarget:self action:@selector(dragGestureChanged:scrollView:)];

trojanfoe在他的回答中所写的是在@selector中使用多个参数的正确方法。请更详细地解释您要做什么,也许您可以采用另一种方法。 - matsr
@Fischer 这个问题是关于选择器的外观,与手势识别器的功能无关。请查看被接受的答案以获取更多详细信息。 - trojanfoe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接