原始屏幕截图:
1。。当键盘不可见时:
哪个很好。
2。问题是,当键盘出现时,上述图像从textView和键盘的原始位置移到上方,如下所示:
这就是我想要做的:
代码:
func addKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
// MARK: - remove Keyboard Observers
func removeKeyboardObservers() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
// MARK: - keyboard show
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height - bottomLayoutGuide.length
UIView.animate(withDuration: 0.25, animations: {() -> Void in
self.bottomConstraint.constant = keyboardHeight
self.view.layoutIfNeeded()
}, completion: nil)
}
}
// MARK: - keyboard hide
@objc func keyboardWillHide(_ notification: Notification) {
view.layoutIfNeeded()
}
当我使用此代码时,请向我显示下面给出的空白屏幕截图:
当我发表评论时,这些行的屏幕截图如下:
// MARK: - keyboard show
@objc func keyboardWillShow(_ notification: Notification) {
// if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
// let keyboardRectangle = keyboardFrame.cgRectValue
// let keyboardHeight = keyboardRectangle.height - bottomLayoutGuide.length
// UIView.animate(withDuration: 0.25, animations: {() -> Void in
// self.bottomConstraint.constant = keyboardHeight
// self.view.layoutIfNeeded()
// }, completion: nil)
// }
}
这是我的主要StoryBoard屏幕截图:
有人可以向我解释如何解决此问题,我已经尝试解决此问题,但没有结果。
任何帮助将不胜感激。
谢谢。
答案 0 :(得分:0)
答案 1 :(得分:0)
您会在新手机上经常看到此“间隙”,因为它们使用“ safeAreaInsets”,并且要减小对象和键盘之间的间隙,您需要做两件事。
let safeArea = view.safeAreaInsets.bottom // This will result CGFloat
不仅减小两个值,您还将获得完美的输出。
如果使用约束,则可以更改底部锚点的常数。
在此示例中,我将使用TableView,但是您可以将其应用于任何对象。
var bottomAnchor: NSLayoutConstraint? // Creating variable for bottom constraint
// Setting Constraints
bottomAnchor = tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
bottomAnchor.isActive = true
// Modifying Constraint later (When Keyboard is Shown)
bottomAnchor.constant = keyboardFrame.height - safeArea
如果要修改UIEdgeInsets,则只需将底值减小到安全区域即可。
// When Keyboard is Shown
// E.g.
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height - safeArea, right: 0)