简体   繁体   中英

“Unrecognized Selector Error” While Using Gesture Recognizer

I receive the following error when tapping on a view:

2015-08-04 15:42:16.236 jake-and-bailey[12158:607] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MainMenuViewController openSettingsPage]: unrecognized selector sent to instance 0x7af560f0'

I added the following gesture recognizer to that view:

Interface:

#import <UIKit/UIKit.h>

@interface OpenSettingsGestureRecognizer : UITapGestureRecognizer

@property UIViewController* viewController;

- (instancetype) initWithViewController: (UIViewController*) viewController;

@end

Implementation:

#import "OpenSettingsGestureRecognizer.h"
#import "SettingsViewController.h"

@implementation OpenSettingsGestureRecognizer

- (instancetype) initWithViewController: (UIViewController*) viewController {
    self = [super initWithTarget:viewController
                          action:@selector(openSettingsPage)];
    if (self) {
        _viewController = viewController;
    }
    return self;
}

- (void) openSettingsPage {
    if (_viewController != nil) {
        [_viewController presentViewController:[[SettingsViewController alloc] init]
                                      animated:YES
                                    completion:nil];
    }
}

@end

For whatever reason the method openSettingsPage is being called from my MainMenuViewController class rather than the OpenSettingsGestureRecognizer class.

Change the target to self and you're good to go like so:

 self = [super initWithTarget:self
                          action:@selector(openSettingsPage)];

Read about target-action design pattern here

You're initializing the UITapGestureRecognizer 's target with whichever UIViewController you're using to initialize its OpenSettingsGestureRecognizer subclass. Try changing:

self = [super initWithTarget:viewController
                      action:@selector(openSettingsPage)];

to

self = [super initWithTarget:self
                      action:@selector(openSettingsPage)];

if you want the target to be OpenSettingsGestureRecognizer instead of MainMenuViewController (which I assume this the UIViewController you're using to initialize the gesture).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM