Mono.WTF
Mono.WTF

Reputation: 1607

Swift 3 - Detecting new lines in UITextView

I'm trying to count (real-time) new lines on UITextView, I found the below method that works well but I actually need to add more features but I don't know how to do.

func textViewDidChange(_ textView: UITextView) {
    let pos = textView.endOfDocument
    let currentRect = textView.caretRect(for: pos)
    if previousRect != CGRect.zero {
        if currentRect.origin.y > previousRect.origin.y {
            //increase the counter
            counter += 1
        }
    }
    previousRect = currentRect
}

Ok so, the code works fine, but I need to:

  1. decrease the counter counter -= 1 when the user delete a line
  2. actually this code increase the counter when new line is detected, instead I need to increase the counter when the return button on the keyboard is pressed giving the user the possibility to exceed the frame width of the text view without increase the counter

I don't know how to do that, do you have any suggestions?

EDIT (Visual Example)

enter image description here

the output here is 4

Upvotes: 0

Views: 3619

Answers (2)

Mono.WTF
Mono.WTF

Reputation: 1607

I solved the problem by myself, I will post the code below if someone need it (check comments in the code):

func textViewDidChange(_ textView: UITextView) {
    let pos = textView.endOfDocument
    let currentRect = textView.caretRect(for: pos)
    if previousRect != CGRect.zero {
        if currentRect.origin.y > previousRect.origin.y {
            // Array of Strings
            var currentLines = textView.text.components(separatedBy: "\n")
            // Remove Blank Strings
            currentLines = currentLines.filter{ $0 != "" }
            //increase the counter counting how many items inside the array
            counter = currentLines.count
        }
    }
    previousRect = currentRect
}

Upvotes: 1

Barbara R
Barbara R

Reputation: 1057

You could listen to every individual character change and just check if it's the new line or not with this delegate function https://developer.apple.com/reference/uikit/uitextviewdelegate/1618630-textview

Upvotes: 0

Related Questions