我正在创建一个自定义的UITableViewController(SATableViewController)类,我可以继承这个类,它将提醒我何时应该从文本字段等处辞第一个响应者。
但是,在加载视图(下面的代码中指示的viewDidLoad,[self.tableView addGestureRecognizer:_tapGestureRecognizer];
行)时,会抛出以下异常:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
手势识别器被分配并初始化就好了,所以我很难过为什么会这样。这个手势识别器的东西都是RootTableViewController的一部分,它运行得很好。
这就是我所拥有的(相关部分):
SATableViewController.h:
#import <UIKit/UIKit.h>
@interface SATableViewController : UITableViewController <UIGestureRecognizerDelegate>
@end
SATableViewController.m:
@interface SATableViewController ()
@property (nonatomic, strong) UIGestureRecognizer *tapGestureRecognizer;
@end
@implementation SATableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// add gesture to detect when table view is being tapped so that keyboard may be dismissed
self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(dismissKeyboard)];
_tapGestureRecognizer.delegate = self;
_tapGestureRecognizer.cancelsTouchesInView = NO;
[self.tableView addGestureRecognizer:_tapGestureRecognizer]; // EXCEPTION THROWN HERE
}
//...
//see: http://stackoverflow.com/questions/7195661/why-is-uigesturerecognizer-being-called-on-my-textfield-clear-button
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if([touch.view isKindOfClass:[UITextField class]] ||
[touch.view isKindOfClass:[UIButton class]])
{
return NO;
}
return YES;
}
- (void)dismissKeyboard {
// to be overidden by subclass -- called when text field should be dismissed
}
//...
- (void)scrollViewWillBeginDragging:(UIScrollView *)activeScrollView {
[self dismissKeyboard];
}
RootTableViewController.h:
#import <UIKit/UIKit.h>
#import "SATableViewController.h"
@interface RootTableViewController : SATableViewController
@end
RootTableViewController.m:
@interface RootTableViewController ()
@property (nonatomic, strong) UIGestureRecognizer *tapGestureRecognizer;
@end
@implementation RootTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)dismissKeyboard {
if ([_textField isFirstResponder]) {
[_textField resignFirstResponder];
}
}
//...
答案 0 :(得分:0)
刚想通了。这是因为我没有摆脱 RootTableViewController.m 中的@property (nonatomic, strong) UIGestureRecognizer *tapGestureRecognizer;
。
所以
@interface RootTableViewController ()
@property (nonatomic, strong) UIGestureRecognizer *tapGestureRecognizer;
@end
应该是
@interface RootTableViewController ()
@end