Ali Fadlallah
Ali Fadlallah

Reputation: 3

TextView Counter On Typing And Count New Line Swift IOS

I want to count newlines ("\n") in a textview.

Or, more specifically, I want to make textview box to count the characters when typing ( +1 ) in label. Also count ( +2 ) when the text have new line and counter ( Label ) must be continuous.

Here is my code:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let allowedChars = 70
    let charsInTextView = -txtmessage.text.count
    let remainingChars = allowedChars + charsInTextView

    if (text == "\n") {
        let remainingChars = 70 - (txtmessage.text.count * 2 )

        countlabel.text = String(remainingChars)
    }

    if (text != "\n"){
        countlabel.text = String(remainingChars)
    }

    return true
}

Upvotes: 0

Views: 1993

Answers (1)

Josh Homann
Josh Homann

Reputation: 16327

import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
    let textView = UITextView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 100)))
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(textView)
        textView.delegate = self
        textView.backgroundColor = .white
    }
}

extension ViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        guard let text = textView.text else  {
            return
        }
        let totalLength = text.count
        let newlineCount = text.filter {$0 == "\n"}.count
        print("Total characters are \(totalLength) of which \(newlineCount) are newLines total of all characters counting newlines twice is \(totalLength + newlineCount)")
    }
}
let v = ViewController()
v.preferredContentSize = CGSize(width: 1024, height: 768)
PlaygroundPage.current.liveView = v

Upvotes: 1

Related Questions