我的代码有问题:当我点击UITextView并且键盘显示时,有一个滚动到顶部(我真的不知道为什么!)我必须向下滚动以返回到UITextView。
我在一个tableView中,我的细胞有动态的高度。
这是我的问题的一个小演示:
我做了一些研究,我试过这个:
@objc func keyboardWillShow(_ notification: NSNotification) {
print("show")
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillHide(_ notification: NSNotification) {
print("hide")
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
它仍然无法正常工作。这真的很奇怪,因为这是我遇到这个问题的唯一观点。
如果您有对textView的引用,请尝试在keyboardWillShow函数中添加此代码。
scrollView.scrollRectToVisible(textView.frame, animated: true)
当您在UITextView
内部点击时,它将成为第一个响应者,如果您阅读文档,它会明确指出:
...某些系统视图(如表视图)可以帮助您自动将第一个响应者滚动到视图中。 ...
这是一个内置功能。
无论如何,你可以尝试从UITableView
中删除键盘观察者。
NotificationCenter.default.removeObserver(tableView, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
我遇到过类似的问题。当您向上和向下滚动时,自动调用scrollViewWillBeginDragging方法。
iOS使用UIScrollViewDelegate来确定用户平移手势的方向。
可能对您有所帮助。
斯威夫特4
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
let translation: CGPoint = scrollView.panGestureRecognizer.translation(in: scrollView.superview)
if translation.y > 0 {
// react to dragging down
}
else {
// react to dragging up
view.endEditing(true)
}
}
目标C.
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];
if(translation.y > 0)
{
// react to dragging down
} else
{
// react to dragging up
[self.view endEditing:YES];
}
}
我的解决方案是分离细胞。
在我的情况下,我在一个单元格中有大约3个文本字段,横跨整个视图。因此,当单击视图底部的文本字段时,我将获得与您完全相同的行为。 (我有一个收藏视图)
事实证明,它滚动回到单元格的顶部(indexpath.row = 0)。所以我创建了第二个单元格(indexpath.row = 1),只包含三个文本字段。现在它滚动了那个单元格的顶部(indexpath.row = 1),这是完美的。
我不知道是什么原因。