gpt4 book ai didi

swift - 键盘高度变化观察者 swift

转载 作者:搜寻专家 更新时间:2023-10-31 22:13:24 24 4
gpt4 key购买 nike

如何在 iOS swift 中检测键盘高度变化或键盘变化?
看我下面的代码,它在文本键盘和表情符号键盘中显示了非常小的一行:

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

此通知将在键盘出现、表情符号更改、显示/隐藏预测时向我们提供键盘框架矩形!

关于swift - 键盘高度变化观察者 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38651636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com