我正在使用键盘通知底视图。
我在情节提要中给出了底视图约束,如下所示:
bottom to safe area = 0, leading, trailing = 0 , height = 80
i phone8效果很好,但是在iphone11中,bottomview与设备底部之间的距离越来越小,所以,如果我将底部约束更改为0到superview,则bottomview不会出现键盘
这里是代码:
class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet weak var customView: UIView!
@IBOutlet weak var msgTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
}
@objc func handleKeyboardNotification(_ notification: Notification) {
if let userInfo = notification.userInfo {
let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.customView.superview?.setNeedsLayout()
//self.customView.superview?.layoutIfNeeded()
}
}
请帮助我。
该问题可能是由于对keyboardWillHide和keyboardWillShow通知使用了相同的选择器。您需要使用以下代码将它们分开:
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidAppear(notification:)), name:
NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidDisappear(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardDidAppear(notification:Notification){
let info = notification.userInfo
let value = info![UIKeyboardFrameEndUserInfoKey] as? NSValue
let rawFrame = value?.cgRectValue
let keyboardFrame = view.convert(rawFrame!, from: nil)
bottomConstarint?.constant = keyboardFrame.size.height
tableView.scrollToBottom()
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
@objc func keyboardDidDisappear(notification:Notification){
bottomConstarint?.constant = 0
tableView.scrollToBottom()
}