Say I want to check if the last 5 characters typed in a UITextView
are "mouse". How would I go about doing this? Specifically in Swift because of how strings indexes are different from Objective-C due to how emojis and the like are stored.
I cannot seem to figure this out. And keep in mind the last n characters may not be typed at the end of the text view, the cursor could be in the middle of the text.
per swift 4, you can simply use
textView.text.last
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()
You can use
substringFromIndex
withtextView.text
.. Thus the last 5 characters can be obtained by this code.