LoginSignup
0
0

More than 1 year has passed since last update.

[Swift][Xcode]TextFieldの入力で表示したキーボードを閉じる方法

Last updated at Posted at 2022-07-28

TextFieldをタップして表示させるキーボードが閉じないせいでその下の項目が永遠に見えない!
という現象の解決策です


TextField以外をタッチしたときにキーボードを閉じる

下記コード

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

キーボードのReturnボタン押下で閉じる

下記コード

extension MainViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

delegateを対象のTextFieldに設定する

    @IBOutlet weak var inputTextField: UITextField!

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


全体コード

全体で見るとこんな感じです

import UIKit

class MainViewController: UIViewController {
    
    @IBOutlet weak var inputTextField: UITextField!

    override func viewDidLoad() {
        // delegate設定
        inputTextField.delegate = self
        super.viewDidLoad()
    }
    
    //textField以外の部分のタッチ時にキーボード閉じる
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
}

extension MainViewController: UITextFieldDelegate {
    //returnボタンを押したタイミングで起動
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

おまけ(OutletCollectionsの場合のdelegate設定方法)

↓にまとめたのでご参照ください。
https://qiita.com/timustan/items/ba93280f9cf347f383d0


参考:https://yamamtoblog.com/textfield-keyboard-close/

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