Swift中键盘消失动画导致UITableView触摸位置异常的解决咨询
解决UITableView键盘隐藏动画中触摸位置错误的问题
针对你遇到的键盘隐藏动画过程中,UITableView的didSelectRowAt事件触摸位置不正确的问题,提供以下几种可行方案:
方案1:点击TableView时立即更新布局(跳过动画)
当用户点击TableView区域时,终止键盘隐藏的动画,直接将布局更新到键盘隐藏后的状态,确保触摸点对应的单元格是正确的。
在处理外部点击的手势回调中添加判断逻辑:
@objc func handleTapOutsideTextField(_ gesture: UITapGestureRecognizer) { let tapPoint = gesture.location(in: view) // 判断点击是否落在TableView范围内 if tableView.point(inside: tapPoint, with: nil) { UIView.performWithoutAnimation { // 立即更新布局到键盘隐藏后的状态 keyboardHandler.hideKeyboard() view.layoutIfNeeded() } // 手动触发正确的行选择事件 if let indexPath = tableView.indexPathForRow(at: tapPoint) { tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) tableView.delegate?.tableView?(tableView, didSelectRowAt: indexPath) } } else { // 非TableView区域正常执行键盘隐藏动画 keyboardHandler.hideKeyboard() } }
方案2:同步TableView的ContentOffset与键盘动画
在键盘隐藏的动画过程中,实时更新TableView的contentOffset,让单元格的位置与屏幕触摸点保持对应,确保坐标转换正确。
监听键盘隐藏通知(或利用你使用的键盘库的回调),添加同步逻辑:
func handleKeyboardWillHide(_ notification: Notification) { guard let userInfo = notification.userInfo, let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval, let curveRawValue = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt, let keyboardEndFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } let animationOptions = UIView.AnimationOptions(rawValue: curveRawValue) let deltaY = keyboardEndFrame.height // 底部栏移动的距离等于键盘高度 UIView.animate(withDuration: duration, delay: 0, options: animationOptions) { // 更新底部栏约束 self.bottomBarBottomConstraint.constant = 0 // 同步调整TableView的contentOffset self.tableView.contentOffset = CGPoint(x: 0, y: self.tableView.contentOffset.y - deltaY) self.view.layoutIfNeeded() } }
方案3:动画期间禁用TableView交互(体验妥协)
如果可以接受用户需等待动画结束才能操作TableView,可在键盘隐藏动画开始时禁用交互,动画完成后恢复:
func handleKeyboardWillHide(_ notification: Notification) { guard let userInfo = notification.userInfo, let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else { return } tableView.isUserInteractionEnabled = false UIView.animate(withDuration: duration) { self.view.layoutIfNeeded() } completion: { _ in self.tableView.isUserInteractionEnabled = true } }
优先推荐方案1或方案2,能在保证用户体验的前提下解决触摸位置错误的问题。
内容的提问来源于stack exchange,提问作者Gargo
相关产品推荐
相关产品推荐

