21
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

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

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が呼ばれているようです

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
21
Help us understand the problem. What are the problem?