当我按下屏幕下方的UITextField
时,它被键盘隐藏了。 我想做的是使用标准的iOS动画向上移动视图,达到我插入文本的UITextField
。 我正在Swift 5(Xcode 10.2) 中开发应用程序
我达到的结果是,现在我可以移动视图(比预期早一点),但是每次我按下UITextField
时视图都会移动,而不仅仅是键盘会隐藏
class ViewController: UIViewController {
deinit {
NotificationCenter.default.removeObserver(self)
}
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) {
guard let userInfo = notification.userInfo else {
return
}
guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardFrame = keyboardSize.cgRectValue
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardFrame.height
}
}
@objc func keyboardWillHide(notification: NSNotification) {
guard let userInfo = notification.userInfo else {
return
}
guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardFrame = keyboardSize.cgRectValue
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y += keyboardFrame.height
}
}
}
我想得到的结果是,如果用户按下将被键盘隐藏的UITextField
,那么,在键盘出现后一点点,视图将向上移动,直到用户可以看到按下的UITextField
。
我已经寻找了很长时间来解决这个问题的方法,但我看到的所有其他方法似乎都已经过时了,或者没有做我想要实现的目标。
你可以通过滚动视图来尝试:
import UIKit
class ViewController: UIViewController {
@IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self,selector:#selector(self.keyboardWillShow),name:UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardWillHide),name:UIResponder.keyboardDidHideNotification, object: nil)
}
@objc func keyboardWillShow(notification: Notification) {
guard let userInfo = notification.userInfo,
let frame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
else{
return
}
let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: frame.height, right: 0)
scrollView.contentInset = contentInset
}
@objc func keyboardWillHide(notification: Notification)
{
scrollView.contentInset = UIEdgeInsets.zero
}
}