Help us understand the problem. What is going on with this article?

UITextFieldDelegateのメソッドの呼ばれるタイミング

More than 5 years have passed since last update.

UITextFieldDelegateのメソッドが呼ばれるタイミングのメモ
今回は以下の4つのメソッドのタイミングを見ていきます

  • textFieldShouldReturn
  • textFieldDidBeginEditing
  • textFieldShouldBeginEditing
  • textFieldShouldEndEditing
  • textFieldDidEndEditing

コード

CiewController.swift
class ViewController: UIViewController, UITextFieldDelegate {
    private let tf:UITextField = UITextField(frame: CGRect(x: 30, y: 30, width: 100, height: 50))

    override func viewDidLoad() {
        super.viewDidLoad()
        tf.placeholder = "test"
        tf.delegate = self
        self.view.addSubview(tf)
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        print("textFieldShouldReturn before responder\n")
        tf.resignFirstResponder()
        print("textFieldShouldReturn\n")
        return true
    }

    func textFieldDidBeginEditing(textField: UITextField) {
        print("textFieldDidBeginEditing\n")
    }

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        print("textFieldShouldBeginEditing\n")
        return true
    }

    func textFieldShouldEndEditing(textField: UITextField) -> Bool {
        print("textFieldShouldEndEditing\n")
        return true
    }

    func textFieldDidEndEditing(textField: UITextField) {
        print("textFieldDidEndEditing\n")
    }
}

キーボード起動時

textFieldShouldBeginEditing
textFieldDidBeginEditing

リターン押下時

textFieldShouldReturn before responder
textFieldShouldEndEditing
textFieldDidEndEditing
textFieldShouldReturn

textFieldShouldReturn before responder と textFieldShouldReturn の間にtextFieldShouldEndEditing, textFieldDidEndEditingが来ているので、resignFirstResponder()内でtextFieldShouldEndEditing, textFieldDidEndEditingが呼ばれているようです

kwst
Front Engineer
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away