我想在textview中计算换行符(“\ n”)。
或者,更具体地说,我想在标签中键入(+1)时使用textview框来计算字符数。当文本有新行时计数(+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
}
答案 0 :(得分:0)
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