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.

[Swift5] テキストフィールド / キーボード操作のメソッド

Last updated at Posted at 2021-03-13

初期化

UITextFieldDelegate をViewControllerから継承する

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var userNameTextField: UITextField!
    @IBOutlet weak var passWordTextField: UITextField!
       
    override func viewDidLoad() {
        super.viewDidLoad()
        
        userNameTextField.delegate = self
        passWordTextField.delegate = self
    }

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

touchesBeganメソッド内で view.endEditing(true)する

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

ezgif-2-bafa0759f409.gif

リターンキーを押した時にキーボードを閉じる

textFieldShouldReturnメソッド内で、textField.resignFirstResponder()

//リターンキーを押したときにキーボードを閉じる
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        //キーボードが閉じるよ
        textField.resignFirstResponder()
        return true
}

ezgif-2-b6f2ef47097a.gif

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?