Tom's Memo

日々の記録と趣味と個人的メモ

【iPhone開発】UITableView上にあるUITextViewキーボードを閉じたい

2012-06-28 16:28:39 | メモ
UITableView上にあるUITextViewキーボードの閉じ方で
UINavigationControllerにボタンを配置して閉じる方法でハマったのでメモ


まずは簡単に以下のように実装

// 各CellにObjectをセット
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath {
TableCell *cell = (TableCell *)[tableView dequeueReusableCellWithIdentifier:ID];

UITextView *textView = [[[UITextView alloc] initWithFrame:CGRectMake(95, 7, 200, 30)] autorelease];
textView.delegate = self;
textView.editable = YES;
[cell.cellView addSubview:textView];
return cell;
}

// キーボードを閉じる処理
- (BOOL)onDissmissKeyboard:(UITextView *)textView{
[textView resignFirstResponder];
return YES;
}

// UITextViewをタップし編集モード開始したタイミングで
// UINavigationControllerにキーボードを閉じるボタンを配置
// ボタン押下時処理はonDissmissKeyboardを呼び出す。
-(void)textViewDidBeginEditing:(UITextView *)textView{
UIBarButtonItem *btnClose = [[[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStyleDone target:self action:@selector(onDissmissKeyboard:)]autorelease];
self.navigationItem.leftBarButtonItem = btnClose;
}

// UITextView編集モード終了時UINavigationControllerに配置したボタンを非表示にする。
- (void)textViewDidEndEditing:(UITextView *)textView {
[self.navigationItem setLeftBarButtonItem:nil animated:NO];
}


この実装だと延々とキーボードを閉じる処理にてエラーが発生した。

-[EditTextViewController onDissmissKeyboard:textView:]: unrecognized selector sent to instance 0x4e60710
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[EditTextViewController onDissmissKeyboard:textView:]: unrecognized selector sent to instance 0x4e60710'
*** Call stack at first throw:
(
0 CoreFoundation 0x010575a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x011ab313 objc_exception_throw + 44
2 CoreFoundation 0x010590bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00fc8966 ___forwarding___ + 966
4 CoreFoundation 0x00fc8522 _CF_forwarding_prep_0 + 50
5 UIKit 0x003404fd -[UIApplication sendAction:to:from:forEvent:] + 119
6 UIKit 0x00552cc3 -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 156
7 UIKit 0x003404fd -[UIApplication sendAction:to:from:forEvent:] + 119
8 UIKit 0x003d0799 -[UIControl sendAction:to:forEvent:] + 67

・中略

21 GraphicsServices 0x019ae289 GSEventRun + 115
22 UIKit 0x0034ec93 UIApplicationMain + 1160
23 editText 0x000255cc main + 102
24 editText 0x000022d5 start + 53
)
terminate called after throwing an instance of 'NSException'
Current language: auto; currently objective-c
(gdb)

どうもFirstResponderがフォーカスしているObjectがUITextViewではなく
BarButtonItemになっているのが原因ぽい。。。

対処するにはキーボードを閉じるのではなく、編集モードを終了することにより
キーボードを閉じればよいので、キーボード閉じる処理を以下のように修正。

- (BOOL)onDissmissKeyboard:(UITextView *)textView{
// [textView resignFirstResponder];
[self.view endEditing:YES];
return YES;
}

これで想定通りの動きになった。

ここにたどり着くまでに2日ぐらいかかったけどなんとか解決!