0

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.

Doug Smith
  • 29,668
  • 57
  • 204
  • 388

3 Answers3

1

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
    }
}
OrderAndChaos
  • 3,547
  • 2
  • 30
  • 57
  • @araferna Long time since I looked at this. The count is from the last cursor position not the end of the string it doesn't matter where the user types as far as I recall. – OrderAndChaos Jun 12 '20 at 14:49
0

You can use substringFromIndex with textView.text.. Thus the last 5 characters can be obtained by this code.

let strLast5: String =  textView.text.substringToIndex(countElements(textView.text) - 5);
Sudhin Davis
  • 2,010
  • 13
  • 18
0

per swift 4, you can simply use textView.text.last

Raditya Kurnianto
  • 734
  • 1
  • 16
  • 42