TextView 计数器键入和计数换行 Swift IOS
Posted
技术标签:
【中文标题】TextView 计数器键入和计数换行 Swift IOS【英文标题】:TextView Counter On Typing And Count New Line Swift IOS 【发布时间】:2018-04-10 17:13:23 【问题描述】:我想在文本视图中计算换行符(“\n”)。
或者,更具体地说,我想让 textview 框在标签中键入 ( +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
【问题讨论】:
【参考方案1】: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
【讨论】:
以上是关于TextView 计数器键入和计数换行 Swift IOS的主要内容,如果未能解决你的问题,请参考以下文章
因为使用 BaseAdapter 在网格视图中重复 textview 产品计数器
如何在Firebase中获取用户数作为计数在android TextView中
swift进阶七:引用计数(Strong、Unowned、Weak)