始めに
NSNotificationCenter
に
UIKeyboardWillShowNotification
と UIKeyboardDidShowNotification
を登録し
両方の通知がちゃんと上がってきているのにソフトキーボードが開かないことがあったので
そのとき調べたことを書く。
コード
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let textField = UITextField(frame: CGRect(x: 100, y: 100, width: 50, height: 30))
textField.backgroundColor = UIColor.redColor()
view.addSubview(textField)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)
}
}
extension ViewController {
func keyboardWillShow(notification: NSNotification) {
print("willShow1")
view.endEditing(true)
print("willShow2")
}
func keyboardDidShow(notification: NSNotification) {
print("didShow")
}
}
結果
これを実行し、textField
にフォーカスを当てると以下のように出力される。
willShow1
didShow
willShow2
考察
UIView.endEditing
を呼ぶと、即座にUIKeyboardDidShowNotification
の通知が上がってくるらしい。実際にはキーボードは表示されてないのに。
(Frameworkの整合性、という問題で仕方ないんだとは思うけど。)
今回のようにわかりやすい場合はすぐ気付くが、keyboardWillShow()
から呼んでいるメソッドの奥深くでView.endEditing
を呼んでいる、みたいなことがあると気付きづらい気がする。
(作り的にどうなんだ、って話は別にして。)
終わりに
NSNotificationCenter
の通知が同期なことに違和感あるの僕だけでしょうか。