LoginSignup
2
2

More than 5 years have passed since last update.

UIKeyboardDidShowNotificationが上がってきているのにキーボードが開かないことがある話

Posted at

始めに

NSNotificationCenter
UIKeyboardWillShowNotificationUIKeyboardDidShowNotification を登録し
両方の通知がちゃんと上がってきているのにソフトキーボードが開かないことがあったので
そのとき調べたことを書く。

コード

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の通知が同期なことに違和感あるの僕だけでしょうか。

2
2
2

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
2
2