LoginSignup
143

More than 5 years have passed since last update.

【Swift】TextFieldのキーボードを閉じる方法3選

Last updated at Posted at 2017-07-03

TextFieldのキーボードを閉じる方法をまとめてみました。

032d4bb4a0add2be1948bec3e048227f.gif

1. 「return」キーを押す

コードベース

resignFirstResponder()メソッドを利用します。

ViewController.swift
import UIKit

class ViewController: UIViewController, UITextFieldDelegate{

    @IBOutlet weak var inputText: UITextField!
    @IBOutlet weak var outputText: UILabel!

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

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

storyboardベース

Xcodeのイベントアクションを利用します。

スクリーンショット 2017-06-26 22.56.36.png

①TextFieldの上で右クリック(二本指でタップ)
②「Sent Events」の「Did End On Exit」を「control」キーを押しながらドラッグ
③「Name」をつけて「Connect」

スクリーンショット 2017-06-26 22.59.41.png

コードが追加されたことを確認できます。

ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var outputText: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func inputText(_ sender: UITextField) {
        outputText.text = sender.text
    }
}

他にも様々なイベントアクションがあるので覚えておくと簡単に実装できます。
参考記事:ボタンによるイベント処理 – swiftによるiOSアプリ開発

2. ボタンを押す

endEditing()メソッドを利用します。
(resignFirstResponder()メソッドでも実装可能です。)

005c8194729f917d5f8db590273fd42b.gif

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var inputText: UITextField!
    @IBOutlet weak var outputText: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func button(_ sender: Any) {
        outputText.text = inputText.text
        // キーボードを閉じる
        inputText.endEditing(true)
    }
}

3. TextField以外の部分をタッチ

touchesBeganメソッドをオーバーライドします。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var outputText: UILabel!

    @IBOutlet weak var inputText: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

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

以上をうまく組み合わせることでユーザーにストレスを与えない実装になりそうです。

参考記事

UITextFieldの入力後に入力用キーボードを閉じる方法

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
143