LoginSignup
1
1

【Swift5】キーボードを閉じる方法

Last updated at Posted at 2021-10-06

はじめに

この記事は、アプリを作っている際に幾度も「なんだっけ?」を解決するために作成した記事です。記事というか公開ノートのようなものです。

前提

class に UITextFieldDelegate を追加します。

import UIKit

class ViewController: UIViewController, UITextFieldDele{

    @IBOutlet weak var TextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        TextField.delegate = self
    }

TextField は任意の textField です。

タッチでキーボードを閉じる

キーボード以外の場所をタップするとキーボードが閉じます。

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        view.endEditing(true) //編集を終了するかを聞く=>true
    }

リターンキーでキーボードを閉じる

キーボードの Return をタップするとキーボードが閉じます。

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        textField.resignFirstResponder() //キーボードを閉じる
        
        return true
    }

#最後に
別の方法があったら追記していきたいと思います。

1
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
1
1