【问题标题】:Get the keyboard height Using NSNotificationCenter, is not working in Swift 4.1使用 NSNotificationCenter 获取键盘高度,在 Swift 4.1 中不起作用
【发布时间】:2018-04-11 14:26:37
【问题描述】:

我正在开发键盘扩展应用程序,我需要默认键盘的高度。

为了获得键盘的高度,我尝试了几十种解决方案like this,但从未调用过 Selector 函数。 还有其他方法可以找到默认键盘的高度吗?

【问题讨论】:

标签: ios swift


【解决方案1】:

此代码将显示您的键盘高度 -

func showKeyboard(notification: NSNotification) {
            if let sizeOFkeyboard = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
                let keyboardHeight = keyboardSize.height
            }
    }

【讨论】:

    【解决方案2】:

    这在 Swift 4.1 中非常适合我:

    var keyboardHeight: CGFloat = 0.0
    
    override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(true)
    
            // Register Notification, To know When Key Board Appear.
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: Notification.Name.UIKeyboardWillShow, object: nil)
    
            // Register Notification, To know When Key Board Hides.
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        }
    
        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(true)
    
            // De register the notifications
            NotificationCenter.default.removeObserver(self)
        }
    
    // MARK: - Keyboard Events
    
        @objc func keyboardWillShow(_ notification: Notification) {
            if let keyboardFrame: NSValue = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue {
                let keyboardRectangle = keyboardFrame.cgRectValue
                keyboardHeight = keyboardRectangle.height
            }
    // use keyboard duration if needed (to animate your view)
            let keyboardDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double
    
        }
    
        @objc func keyboardWillHide(_ notification: Notification) {
    
            let keyboardDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double
    
        }
    

    【讨论】:

    • 再次,我正在处理键盘扩展。这个方法我试过十几次了,还是不行。
    • 嘿,你有没有找到其他解决方案来获取键盘高度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2015-05-06
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    相关资源
    最近更新 更多