问题描述
当键盘开始出现时,我正在向上移动我的文本视图。但是即使键盘完全可见,这个方法也会被触发,并且用户再次点击文本视图。因此,表格视图偏移量不断增加,内容不断移动到屏幕外。
我正在使用 pod KeyboardObserver(为 Swift 5 更新)。它本质上与 NotificationCenter.default.addobserver(self,selector: #selector(handleKeyboardWillChangeFrame(_:)),name: NSNotification.Name.UIKeyboardWillChangeFrame,object: nil)
做同样的事情。
keyboard.observe { [weak self] (event) -> Void in guard let self = self else { return } switch event.type { case .willChangeFrame: self.handleKeyboardWillChangeFrame(keyboardEvent: event) // case .willShow,.willHide: // self.handleKeyboardWillChangeFrame(keyboardEvent: event) default: break } }
@H_502_11@听众:
func handleKeyboardWillChangeFrame(keyboardEvent: KeyboardEvent) { let uiScreenHeight = UIScreen.main.bounds.size.height let endFrame = keyboardEvent.keyboardFrameEnd let endFrameY = endFrame.origin.y let offset = -1 * endFrame.size.height print("Handling keyboard change frame: End Y - ",endFrameY) if endFrameY >= uiScreenHeight { self.discussionsMessageBoxBottomAnchor.constant = 0.0 self.discussionChatView.discussionTableView.contentOffset.y += 2 * offset } else { self.discussionsMessageBoxBottomAnchor.constant = offset self.discussionChatView.discussionTableView.contentOffset.y -= offset } UIView.animate( withDuration: keyboardEvent.duration,delay: TimeInterval(0),options: keyboardEvent.options,animations: { self.view.layoutIfNeeded() },completion: nil) }
@H_502_11@控制台输出:
Handling keyboard change frame: End Y - 737.0 Handling keyboard change frame: End Y - 521.0 Handling keyboard change frame: End Y - 479.0 Handling keyboard change frame: End Y - 479.0 <-- Keyboard visible and TextView tapped Handling keyboard change frame: End Y - 479.0 <-- Keyboard visible and TextView tapped Handling keyboard change frame: End Y - 479.0 <-- Keyboard hiding Handling keyboard change frame: End Y - 812.0 <-- Keyboard hidden
@H_502_11@
编辑
这是我目前的解决方法,但我仍然想知道这里的基本问题是什么。
class discussionsViewController: UIViewController { ... var oldKeyboardEndFrameY: CGFloat = 0 ... func handleKeyboardWillChangeFrame(keyboardEvent: KeyboardEvent) { let uiScreenHeight = UIScreen.main.bounds.size.height let endFrame = keyboardEvent.keyboardFrameEnd let endFrameY = endFrame.origin.y if oldKeyboardEndFrameY == endFrameY { return } oldKeyboardEndFrameY = endFrameY let offset = -1 * endFrame.size.height print("Handling keyboard change frame: End Y - ",endFrameY) if endFrameY >= uiScreenHeight { self.discussionsMessageBoxBottomAnchor.constant = 0.0 self.discussionChatView.discussionTableView.contentOffset.y += 2 * offset } else { self.discussionsMessageBoxBottomAnchor.constant = offset self.discussionChatView.discussionTableView.contentOffset.y -= offset } UIView.animate( withDuration: keyboardEvent.duration,completion: nil) } ... }
@H_502_11@解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)