键盘高度变化观察者迅速 [英] Keyboard height change observer swift

查看:80
本文介绍了键盘高度变化观察者迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测键盘高度变化或iOS swift中的键盘变化?
参见下面的代码,它在文本键盘和Emojis键盘中显示的行很小:

How to detect Keyboard height change, or keyboard change in iOS swift?
See my below code, it shows very small line in text keyboard and Emojis keyboard:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardHideNShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardHideNShow(_:)), name: UIKeyboardWillHideNotification, object: nil)
var didDisplayedKeyboard:Bool = false

func keyboardHideNShow(notification:NSNotification) {

var movement: CGFloat = 0.0
let userInfo:NSDictionary = notification.userInfo!
let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.CGRectValue()

let movementDuration:NSTimeInterval = 0.3
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )

if notification.name == UIKeyboardWillShowNotification {
    // Do the operation only if its hide n show or show n hide
    // When the keyboard switches from text to emoji, it wont hide the previous keyboard. will just replace
    //      In that case we need to avoid the keyboard movement
    if didDisplayedKeyboard == false {
        movement = -keyboardRectangle.height
        didDisplayedKeyboard = true
        print("m\(movement)")
        self.view.frame = CGRectOffset(self.view.frame, 0,  movement)
    }

} else if notification.name == UIKeyboardWillHideNotification {

    movement =  keyboardRectangle.height
    didDisplayedKeyboard = false
    self.view.frame = CGRectOffset(self.view.frame, 0,  movement)
}
UIView.commitAnimations()
}

如何调整视图?

推荐答案

使用UIKeyboardWillChangeFrameNotification通知是这样的:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)

并将更改接收为:

func keyboardWillChangeFrame(notification: NSNotification) {
    if let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
        let keyboardHeight = keyboardFrame.size.height
        print("keyboard height: \(keyboardHeight)")
        //do the chnages according ot this height
    }
}

此通知将在键盘出现,更改表情符号,显示/隐藏预测时为我们提供键盘框架校正!

This notification will give us the keyboard frame rect when keyboard appears, changes to emoji, shows/hides predictions!

这篇关于键盘高度变化观察者迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆