所以我使用 KeyboardDidShow 设置了键盘观察器,这样我就可以仅在显示键盘时向上移动 View 。但是,KeyboardDidShow 在每个 View 启动时运行,并且也在随机时间运行。我尝试过监视键盘框架,并且仅在框架发生变化时才移动 View ,但即使没有显示键盘, View 仍然会经常移动。通常,每当 View 首次启动时都会发生这种情况,因此我尝试添加延迟,但它不太可靠。
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}
@objc func keyboardDidShow(_ notification: Notification) {
let userInfo = notification.userInfo!
let beginFrameValue = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)!
let beginFrame = beginFrameValue.cgRectValue
let endFrameValue = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)!
let endFrame = endFrameValue.cgRectValue
if beginFrame.equalTo(endFrame) {
return
} else {
let indexPath = IndexPath(item: 0, section: 0)
if UIScreen.main.bounds.height == 812 {
collectionView?.contentInset = UIEdgeInsets(top: 318 + view.safeAreaInsets.bottom, left: 0, bottom: 73, right: 0)
}
collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true)
}
}
最佳答案
问题是您配置了错误的通知。不要使用 UIKeyboardDidShow。使用 UIKeyboardWillShow,并检查旧框架、新框架以及新框架是否会覆盖您的 View 。
实现稳健的实现并非易事,但这肯定是一个先前已解决的问题,已在此处多次解释过。
关于swift - 当键盘未显示时调用 KeyboardDidShow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52467718/