我编写了一个函数scrollToVisible()
来滚动UItextview
中的文本,因为文本的某些部分被键盘覆盖,或者光标不可见。但是UItextview
可以在光标不在整个 View 中但不可见时自动滚动文本,它仍然可以通过自动滚动被键盘覆盖。UItextview的自动滚动可以中断我的scrollToVisible( )
。
那么,我可以禁止UItexview自动滚动吗?或者另一种方法来解决“键盘盖”问题?
我的scrollToVisible()函数
func scrollToVisible()
{
let cursortop = self.EditArea.convert(self.EditArea.caretRect(for: (self.EditArea.selectedTextRange?.start)!).origin, to: self.view)
var cursorbottom = cursortop
cursorbottom.y += self.EditArea.caretRect(for: (self.EditArea.selectedTextRange?.start)!).height
let bottom = UIScreen.main.bounds.size.height - self.EditArea.textContainerInset.bottom
var contentOffset = self.EditArea.contentOffset
if cursortop.y <= 85
{
contentOffset.y = contentOffset.y - 85 + cursortop.y
self.EditArea.setContentOffset(contentOffset, animated: true)
}
else if cursorbottom.y >= bottom
{
contentOffset.y = contentOffset.y - bottom + cursorbottom.y
self.EditArea.setContentOffset(contentOffset, animated: true)
}
}
PS:这个EditArea是textview
最佳答案
我有一个类似的问题:当您打开键盘时, TextView 未调整,光标隐藏在键盘后面(或者如您所说“覆盖”光标)。因此,如果我按 Enter 键开始新行,它也不会明显自动滚动(实际上它会自动滚动,但它位于键盘后面)。我在这个网站上找到了一个非常适合我的解决方案:https://www.hackingwithswift.com/example-code/uikit/how-to-adjust-a-uiscrollview-to-fit-the-keyboard
使用 swift 4 从上述网站提取的解决方案:
在 viewDidLoad()
函数中订阅键盘出现和消失时的事件:
// For avoiding that the text cursor disappears behind the keyboard, adjust the text for it
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: .UIKeyboardWillHide, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: .UIKeyboardWillChangeFrame, object: nil)
使用此函数调整 TextView ,将其添加到类中的任何位置:
// Adjusts the textView, so that the text cursor does not disappear behind the keyboard
@objc func adjustForKeyboard(notification: Notification) {
let userInfo = notification.userInfo!
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
if notification.name == Notification.Name.UIKeyboardWillHide {
textView.contentInset = UIEdgeInsets.zero
} else {
textView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
}
textView.scrollIndicatorInsets = textView.contentInset
let selectedRange = textView.selectedRange
textView.scrollRangeToVisible(selectedRange)
}
关于ios - 如何解决UITextView中的 "auto-scroll"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48324745/