"Unrecognized Selector Error" 使用手势识别器时

"Unrecognized Selector Error" While Using Gesture Recognizer

我在点击视图时收到以下错误消息:

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'

我向该视图添加了以下手势识别器:

接口:

#import <UIKit/UIKit.h>

@interface OpenSettingsGestureRecognizer : UITapGestureRecognizer

@property UIViewController* viewController;

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

@end

实施:

#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

无论出于何种原因,方法 openSettingsPage 是从我的 MainMenuViewController class 而不是 调用的OpenSettingsGestureRecognizer class.

将目标更改为 self,这样就可以了:

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

阅读目标-动作设计模式here

您正在使用任何 UIViewController 初始化 UITapGestureRecognizer 的目标来初始化其 OpenSettingsGestureRecognizer 子类。尝试更改:

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

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

如果您希望目标是 OpenSettingsGestureRecognizer 而不是 MainMenuViewController(我假设这是您用来初始化手势的 UIViewController)。