HelloMoon
HelloMoon

Reputation:

What's the trick to pass an event to the next responder in the responder chain?

Apple is really funny. I mean, they say that this works:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch = [touches anyObject];
    NSUInteger numTaps = [touch tapCount];
    if (numTaps < 2) {
        [self.nextResponder touchesBegan:touches withEvent:event];
   } else {
        [self handleDoubleTap:touch];
   }
}

I have a View Controller. Like you know, View Controllers inherit from UIResponder. That View Controller creates a MyView object that inherits from UIView, and adds it as a subview to it's own view.

So we have:

View Controller > has a View (automatically) > has a MyView (which is a UIView).

Now inside of MyView I put that code like above with a NSLog that prints "touched MyView". But I forward the event to the next responder, just like above. And inside the ViewController I have another touchesBegan method that just prints an NSLog a la "touched view controller".

Now guess what: When I touch the MyView, it prints "touched MyView". When I touch outside of MyView, which is the view of the VC then, I get a "touched view controller". So both work! But what doesn't work is forwarding the event. Because now, actually the next responder should be the view controller, since there's nothing else inbetween. But the event handling method of the VC is never called when I forward it.

%$&!§!!

Ideas?

Figured out weird stuff MyView's next responder is the view of the view controller. That makes sense, because MyView is a subview of that. But I didn't modify this UIView from the view controller. it's nothing custom. And it doesn't implement any touch event handling. Shouldn't the message get passed on to the view controller? How could I just let it pass? If I remove the event handling code in MyView, then the event arrives nicely in the view controller.

Upvotes: 18

Views: 27917

Answers (8)

gadu
gadu

Reputation: 1826

If you look at the documentation of UIResponder the description says that by default:

UIView implements this method by returning the UIViewController object that manages it (if it has one) or its superview (if it doesn’t);

If your view isn't returning the view controller, it must be returning its superview then (as you figured out).

UIApplication actually has a method that is supposed to handle this use case exactly:

- (BOOL)sendAction:(SEL)action
                to:(id)target
              from:(id)sender
          forEvent:(UIEvent *)event

Since you don't have a reference to the target, you can work your way up the responder chain by setting target value as nil since according to the documentation:

If target is nil, the app sends the message to the first responder, from whence it progresses up the responder chain until it is handled.

You can of course get access to the UIApplication with its class method [UIApplication sharedApplication]

More info here: UIApplication documents

This is extra, but if you absolutely need access the view controller to do something a little more complex, you can work your way up the responder chain manually until you reach the view controller by calling the nextResponder method until it returns a view controller. For example:

UIResponder *responder = self;
while ([responder isKindOfClass:[UIView class]])
    responder = [responder nextResponder];

then you can just cast it as your view controller and proceed do whatever you wanted to do with it:

UIViewController *parentVC = (UIViewController *)responder

but note that kind of breaks the MVC pattern and likely means you're doing something in a "hacky" way

Upvotes: 3

Avneesh Agrawal
Avneesh Agrawal

Reputation: 944

use this

    [super.nextResponder touchesBegan:touches withEvent:event];

before this line in your code

    [self.nextResponder touchesBegan:touches withEvent:event];

it means

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
     UITouch* touch = [touches anyObject];
     NSUInteger numTaps = [touch tapCount];
     if (numTaps < 2) {
         [super.nextResponder touchesBegan:touches withEvent:event];
         [self.nextResponder touchesBegan:touches withEvent:event];
     } else {
         [self handleDoubleTap:touch];
     }
}

**Swift 4 Version **

func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
    let touch = touches?.first as? UITouch
    let numTaps: Int? = touch?.tapCount
    if (numTaps ?? 0) < 2 {
        if let aTouches = touches as? Set<UITouch> {
            super.next?.touchesBegan(aTouches, with: event)
            next?.touchesBegan(aTouches, with: event)
        }
    } else {
        handleDoubleTap(touch)
    }
}

Upvotes: 1

吴江伟
吴江伟

Reputation: 39

To reference a view controller, you need to use

[[self nextResponder] nextResponder]

because [self nextResponder] means a view controller's view, and [[self nextResponder] nextResponder] means the view controller itself, now you can get the touch event

Upvotes: 2

吴江伟
吴江伟

Reputation: 39

Today I found a better method to fix this or the question like this.

In yours UITableViewCell,you can add a delegate to listen the touch event, like this:

@protocol imageViewTouchDelegate

-(void)selectedFacialView:(NSInteger)row item:(NSInteger)rowIndex;

@end

@property(nonatomic,assign)id<imageViewTouchDelegate>delegate;

Then in yours UITableViewController:your can done like this:

@interface pressionTable : UITableViewController<facialViewDelegate>

and in the .m file you can implemate this delegate interface,like:

-(void)selectedFacialView:(NSInteger)row item:(NSInteger)rowIndex{
//TO DO WHAT YOU WANT}

NOTE:when you init the cell,you must set the delegate,otherwise the delegate is invalid,you can do like this

- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

pressionCell *cell = (pressionCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[pressionCell alloc]initWithFrame:CGRectMake(0, 0, 240, 40)];
}

cell.delegate = self;

}

PS:I know this DOC is old, but I still add my method to fix the question so when people meet the same problem, they will get help from my answer.

Upvotes: 1

Autonomy
Autonomy

Reputation: 412

Had trouble with this, as my custom view was deeper in the view hierarchy. Instead, I climbed the responder chain until it finds a UIViewController;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // Pass to top of chain
    UIResponder *responder = self;
    while (responder.nextResponder != nil){
        responder = responder.nextResponder;
        if ([responder isKindOfClass:[UIViewController class]]) {
            // Got ViewController
            break;
        }
    }
    [responder touchesBegan:touches withEvent:event];
}

Upvotes: 5

twerdster
twerdster

Reputation: 5017

I know this post is old but i thought id share because I had a similar experience. I fixed it by setting the userInteractionEnabled to NO for the view of the view controller that was automatically created.

Upvotes: 1

MikZ
MikZ

Reputation: 364

Yes it should 100% work in common case. I've just tried with test project and everything seems to be ok.

I've created View-Based Application. Using Interface Builder put new UIView up to the present View. Then create new file with subclass of UIView and select just created class for my new view. (Interface Builder->Class identity->Class->MyViewClass)

Add touches handler functions both for MyViewClass and UIViewController.

//MyViewClass

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"myview touches");
[self.nextResponder touchesBegan:touches withEvent:event];
}

//ViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  
  NSLog(@"controller touches");
}   

I see both NSLogs when press MyViewClass. Did you use Interface Builder and XIB file when loading your ViewController or set view programatically with loadView function?

Upvotes: 2

James Eichele
James Eichele

Reputation: 119144

According to a similar question, your method should work.

This leads me to think that your view's nextResponder is not actually the ViewController, as you suspect.

I would add a quick NSLog in your forwarding code to check what your nextResponder really points to:

if (numTaps < 2) {
    NSLog(@"nextResponder = %@", self.nextResponder);
    [self.nextResponder touchesBegan:touches withEvent:event];
}

You can also change your other NSLog messages so that they output type and address information:

NSLog(@"touched %@", self);

touched <UIView 0x12345678>

This should get you started on diagnosing the problem.

Upvotes: 5

Related Questions