LoginSignup
0
1

More than 3 years have passed since last update.

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

Posted at

Swift学習2日目、自分用の備忘録です。

キーボードを閉じる

import UIKit

class ViewController: UIViewController, UITextFieldDelegate { // 1. クラスにUITextFieldDelegateを付与

    @IBOutlet weak var userName: UITextField! // 2. テキストフィールドを紐付け

    override func viewDidLoad() {
        super.viewDidLoad()

        userName.delegate = self // 3.
    }

    // 4. タッチでキーボードを閉じる
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }

    // 5. リターンでキーボードを閉じる
    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