Reputation: 1607
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:
counter -= 1
when the user delete a lineI don't know how to do that, do you have any suggestions?
EDIT (Visual Example)
the output here is 4
Upvotes: 0
Views: 3619
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
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