我编写了一个函数scrollToVisible()
来滚动UItextview
中的文本,因为键盘覆盖了部分文本,或者光标不可见。但是UItextview
可以在光标不在整个视图中但不可见时自动滚动文本,它仍然可以通过键盘自动滚动覆盖.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
答案 0 :(得分:1)
我遇到了类似的问题:当你打开键盘时,文本视图没有被调整,光标隐藏在键盘后面(或者你说&#34;覆盖&#34;光标)。因此,如果我按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)
}
答案 1 :(得分:0)
这是我的解决方案,您只需在app delegate中编写一行代码就可以在app中处理任何textfield / textview
如果您使用的是pod,只需添加以下pod即可添加“IQKeyboardManager”pods
pod'IQKeyboardManagerSwift'
并在app delegate
中的didFinishLaunchingWithOptions中添加此行 IQKeyboardManager.sharedManager().enable = true