Search code examples
iphoneobjective-cdelegatesuislider

How to Use UIGesterRecognizer within Subclass


I have a subclass:

CustomView : UIScrollView. 

Inside of this subclass I have some methods that, say, populate my custom view with some UI elements. I want to add UIGesterRecognizer functionality to these elements but I do not know how to handle setting the delegate and adding selectors:

@implementation  CustomView 

-populateMe{

     UIImageView *iv = [...];
     UIGesterRecognizer r = [UIGesterRecognizer alloc] 
          initWithTarget:self 
          action:@selector(handleMySwipe:); 
                          //<==where to declare handler

     r.delegate = self; //<==COMPILER ERROR self
     [iv.addGestureRecognizer r];
} 

So my problem is where I commented above: self is not a valid delegate (I tried self.superclass) and where do I need to declare a handler for action, i.e. handleMySwipe.

Please explain so I understand.


Solution

  • CustomView is potentially a delegate, if you implement the UIGestureRecognizerDelegate protocol for it. That is, implement a few methods within your CustomView class that the protocol requires you to.

    Once you've done that, you should be able to set the target parameter to self without any errors. Since your target is now self, you need to implement the selector/method handleMySwipe: within your CustomView class because that is where it will look for it (the target).

    - (void) handleSwipe:(UIGestureRecognizer *)gr {
    }