【发布时间】:2018-09-24 00:13:12
【问题描述】:
所以我使用 KeyboardDidShow 设置了键盘观察器,这样我就可以仅在显示键盘时向上移动视图。但是,KeyboardDidShow 在每个视图启动时运行,并且在随机时间运行。我尝试过监控键盘框架,并且仅在框架发生变化时才移动视图,但是即使没有显示键盘,视图也会经常发生变化。通常,每当首次启动视图时都会发生这种情况,因此我尝试添加延迟,但它不是很可靠。
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)
}
}
【问题讨论】:
-
你最好只使用
keyboardDidChangeFrameNotification。它还将通知 kb 几何图形随动画持续时间的变化。当键盘即将显示/隐藏以及旋转设备时调用它 -
我尝试使用keyboardDidChangeFrame,但只要第一次显示视图,它仍然会运行。我在某处读到它们在开始时运行,因为当时(或类似)配置了键盘的框架