This function will return the last n characters from the last cursor position in the textView, unless the cursor position is too close to the start of the string, in which case it will return from the start of the string to the cursor.
To check on each change make the ViewController a delegate of UITextViewDelegate
and implement textViewDidChange()
class ViewController: UIViewController, UITextViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
}
func textViewDidChange(textView: UITextView) {
print(lastNChars(5, textView: textView)!)
}
func lastNChars(n: Int, textView: UITextView) -> String? {
if let selectedRange = textView.selectedTextRange {
let startPosition: UITextPosition = textView.beginningOfDocument
let cursorPosition = textView.offsetFromPosition(startPosition, toPosition: selectedRange.start)
let chars = textView.text as String
var lastNChars: Int!
if n > cursorPosition {
lastNChars = cursorPosition
} else {
lastNChars = n
}
let startOfIndex = chars.startIndex.advancedBy(cursorPosition - lastNChars)
let endOfIndex = chars.startIndex.advancedBy(cursorPosition)
let lastChars = chars.substringWithRange(startOfIndex ..< endOfIndex)
return lastChars
}
return nil
}
}