Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: add a parameter to @selector

When I have this line of code

UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(dragGestureChanged:)];

and this

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

I want to add at "@selector(dragGestureChanged:)" a parameter that is "(UIScrollView*)scrollView", how can I do?

like image 367
cyclingIsBetter Avatar asked Nov 22 '11 15:11

cyclingIsBetter


1 Answers

You can't directly — UIGestureRecognizers 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

And then you can just do:

UILongPressGestureRecognizer = [[UILongPressGestureRecognizerWithBlock alloc] 
        initWithBlock:^(UIGestureRecognizer *recogniser)
        {
            [someObject relevantSelectorWithRecogniser:recogniser 
                      scrollView:relevantScrollView];
        }];
like image 145
Tommy Avatar answered Dec 19 '22 18:12

Tommy