0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】Enter押したときとキーボード領域以外をタッチしたときにキーボードを閉じる

Posted at

どういうことか

たとえばiPhoneでユーザー名入力フォームとかをタッチすると『入力モード』になってキーボードが出てくる。で、タイトルにある行動をしたらキーボードを閉じたい。

はじめに

ViewControllerクラスでUITextFieldに対して『デレゲート』の呪文を使い、我らがアップルのこしらえてくれたメソッドを使えるようにしておく必要がある。

class ViewController: UIViewController,UITextFieldDelegate {
  // 中略
}

閉じる

定型文として使っていいと思う。

  // タッチでキーボードを閉じる
  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
  }
  
  // リターンキーを押したときにキーボードを閉じる
  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
  }
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?