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