问题描述
我有一个登录屏幕。在(X:0,Y:0)
的中间有一个stackView,其中有两个文本字段。当我想在文本字段中输入内容时,将显示键盘并抬起stackView,一旦我输入一个字符,它就会就位,并且看不到任何内容。告诉我在文本字段中输入字符时如何确保stackView不会掉落!
//MARK: Override
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
///NotificationCenter keyboard
NotificationCenter.default.addobserver(self,selector: #selector(keyboardWillShow),name: UIResponder.keyboardWillShowNotification,object: nil)
NotificationCenter.default.addobserver(self,selector: #selector(keyboardWillHide),name: UIResponder.keyboardWillHideNotification,object: nil)
}
override func viewWilldisappear(_ animated: Bool) {
super.viewWilldisappear(animated)
NotificationCenter.default.removeObserver(self)
}
// Extension keyboard SHOW/HIDE
extension LoginViewController {
@objc func keyboardWillShow(notification: NSNotification) {
var keyboardHeight = CGFloat(0.0)
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
keyboardHeight = keyboardRectangle.height
}
UIView.animate(withDuration: 3) {
self.conteinerStackView.frame.origin.y = keyboardHeight - 100
self.view.layoutIfNeeded()
}
}
@objc func keyboardWillHide() {
self.view.layoutIfNeeded()
UIView.animate(withDuration: 1) {
self.conteinerStackView.frame.origin.y = 0
self.view.layoutIfNeeded()
}
}
}
解决方法
有很多解决此问题的方法。
-
无代码插入式通用库可防止键盘向上滑动并覆盖UITextField / UITextView。无需编写任何代码,也不需要进行任何设置。
使用安装或查看文档
pod 'IQKeyboardManagerSwift'
-
使用键盘观察器
override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self,selector: #selector(keyboardWillShow(notification:)),name: UIResponder.keyboardWillShowNotification,object: nil) NotificationCenter.default.addObserver(self,selector: #selector(keyboardWillHide(notification:)),name: UIResponder.keyboardWillHideNotification,object: nil) } @objc func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { self.view.frame.origin.y -= keyboardSize.height } } @objc func keyboardWillHide(notification: NSNotification) { self.view.frame.origin.y = 0 }
尝试将底部约束设置为stackView并在观察器函数中使用它。
@objc func keyboardWillAppear(notification: Notification)
{
let keyboardRect: CGRect = notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! CGRect
let keyboardSize: CGSize = keyboardRect.size
bottomConstraint.constant = keyboardSize.height + 20
}
@objc func keyboardWillDisAppear(notification: Notification)
{
bottomConstraint.constant = 20
}