我想在显示键盘时向上移动屏幕,在隐藏键盘时移动到底部。
我使用此代码:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
但我有这个问题:http://gph.is/2AvLo1A
在此屏幕上,我点击textField显示键盘并点击空白区域以隐藏键盘几次。我的屏幕向下爬,黑色背景填满整个屏幕。如何解决?
更新
显示键盘后,底部有新的空白区域。如果我滚动,我可以看到它:https://imgur.com/a/fFyEC
答案 0 :(得分:1)
将scrollview的底部约束挂钩到superViews的底部并将其拖动为IBOutlet并执行此操作
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
self.scrollviewBottomCon.constant = keyboardSize.height
self.view.layoutIfNeeded()
self.scrollView.scrollRectToVisible((self.textfeild.frame), animated: true)
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
self.scrollviewBottomCon.constant = 0
self.view.layoutIfNeeded()
}
}
答案 1 :(得分:0)
尽量不要上下移动整个视图,而是要移动真正需要移动的组件。我建议使用视图来包含你想要移动的元素。
我有一个用例,我在容器视图下面有一个coupe文本字段和一个提交按钮。当键盘出现时,我希望两个文本字段和按钮上升。这是我处理的方式。
@objc func keyboardWillAppear(_ notification: NSNotification) {
if let userInfo = notification.userInfo,
let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
// Calculate how much to move
let submitButtonHeight = self.submitButton.frame.size.height
var submitButtonOrigin = self.view.convert(self.submitButton.frame.origin, from: self.containerView)
submitButtonOrigin.y = submitButtonOrigin.y + submitButtonHeight + 4.0
var visibleRect = self.view.frame
visibleRect.size.height -= keyboardFrame.height
// If keyboard covers the button, move the container up
if !visibleRect.contains(submitButtonOrigin) {
let keyboardMove = submitButtonOrigin.y - visibleRect.size.height
if keyboardMove > 0 {
UIView.animate(withDuration: 0.3) {
self.containerView.transform = CGAffineTransform(translationX: 0, y: -keyboardMove)
}
}
}
}
}
@objc func keyboardWillDisappear(_ notification: NSNotification) {
UIView.animate(withDuration: 0.3) {
self.containerView.transform = CGAffineTransform.identity
}
}
这可能是也可能不是您的解决方案,但可以提供另一种选择。