Help us understand the problem. What is going on with this article?

UITextField のキーボード非表示に関するメモ

More than 5 years have passed since last update.

一番シンプルな方法

Storyboard アクションを使う

対象の UITextFiled の "Did End On Exit" アクションメソッドを追加して、そこに処理を追加する。すると Enter 押下時にキーボードが非表示になる。

// Storyboard アクションを使う
@interface ViewController : UIViewController
- (IBAction)onDidEndOnExit:(id)sender;
@end

- (IBAction) onDidEndOnExit:(id)sender {
    // 特にハンドラを設けるだけで、何もしなくてもキーボードが非表示になるみたい。
#if 0    
   [sender resignFirstResponder];
    //[self.view endEditing:YES]; // or これでもいいらしい
#endif
}

UITextFieldDelegate を使う方法

// .h ファイル
// UITextFieldDelegate protocol を使う
@interface ViewController : UIViewController <UITextFieldDelegate>
@end

// .m ファイル
- (void)viewDidLoad
{
    // delegate 設定
    [self.textField setDelegate:self];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

おまけ:入力中に他の場所をタッチしたら、キーボードを消したい

GestureRecognizer を使う

  1. 部品として ViewController に Tap GestureRecognizer を追加
  2. Storyboard アクションを追加。(Ctrl押しながらドラッグとか)
    Tap.png

  3. あとは、view の endEditing か UITextField が firstResponder なら、resignFirstResponder を呼び出すように書くだけ。

- (IBAction)onTap:(id)sender {
    [self.view endEditing:YES];

    // 以下のようにも書ける
    //if ( self.textField.isFirstResponder )
    //{
    //    [self.textField resignFirstResponder];
    //}
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした