I'm trying to force UITextView
to keep caret always on the same fixed height, for example in the 1/4 of screen.
I should behave similar to old typewriters - when user presses enter (or reaches end of line) text should scroll one line up and caret should stay in the same y position and jump to the begining of new line.
I was trying to do it like so, but it behaves unexpectedly, caret jumps randomly sometimes and scrolling is visible, it scrolls itself down and then I scroll it up again with scrollRectToVisible
, this do not seem like ideal way of doing it.
How can I achieve such effect? Any library or pod with similar functionality would also be much appreciated.
func setScrollToMiddle() {
if let selectedRange = textView.selectedTextRange {
let caretRect = textView.caretRect(for: selectedRange.start)
let middleOfCaretHeight = caretRect.origin.y + (caretRect.height / 2)
let screenHeight = UIScreen.main.bounds.height
guard let kbSize = self.keyboardSize else { return }
let keyboardHeight = kbSize.height
let visibleTextAreaHeight = screenHeight - keyboardHeight - topMenuView.frame.height
let finalRectY = middleOfCaretHeight - topMenuView.frame.height - (visibleTextAreaHeight / 2)
let finalRect = CGRect(x: 0.0, y: finalRectY, width: textView.frame.width, height: visibleTextAreaHeight)
textView.scrollRectToVisible(finalRect, animated: false)
}
}