TextView 计数器打字并计数新行 Swift IOS

TextView Counter On Typing And Count New Line Swift IOS

我想计算文本视图中的换行符 ("\n")。

或者,更具体地说,我想让 textview 框在标签中键入 (+1) 时计算字符数。当文本有换行和计数器 ( Label ) 必须连续时,也计数 ( +2 )。

这是我的代码:

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
}
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 {[=10=] == "\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