TextView 计数器在键入和计数新行 Swift IOS



我想在文本视图中计算换行符(""(。

或者,更具体地说,我想制作文本视图框以在标签中键入 (+1( 时计算字符数。当文本有新行和计数器(标签(时,还要计数(+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 {$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

相关内容

  • 没有找到相关文章

最新更新