Swift 3 - 在 UITextView 中检测新行 [英] Swift 3 - Detecting new lines in UITextView
本文介绍了Swift 3 - 在 UITextView 中检测新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 UITextView 上计算(实时)新行,我发现下面的方法效果很好,但我实际上需要添加更多功能,但我不知道该怎么做.
I'm trying to count (real-time) new lines on UITextView, I found the below method that works well but I actually need to add more features but I don't know how to do.
func textViewDidChange(_ textView: UITextView) {
let pos = textView.endOfDocument
let currentRect = textView.caretRect(for: pos)
if previousRect != CGRect.zero {
if currentRect.origin.y > previousRect.origin.y {
//increase the counter
counter += 1
}
}
previousRect = currentRect
}
好的,代码工作正常,但我需要:
Ok so, the code works fine, but I need to:
- 当用户删除一行时减少计数器
counter -= 1
- 实际上这段代码在检测到新行时增加了计数器,相反,我需要在按下键盘上的返回按钮时增加计数器,让用户有可能在不增加计数器的情况下超过文本视图的框架宽度
我不知道该怎么做,您有什么建议吗?
I don't know how to do that, do you have any suggestions?
编辑(可视化示例)
这里的输出是 4
推荐答案
我自己解决了问题,如果有人需要我会在下面贴出代码(查看代码中的注释):
I solved the problem by myself, I will post the code below if someone need it (check comments in the code):
func textViewDidChange(_ textView: UITextView) {
let pos = textView.endOfDocument
let currentRect = textView.caretRect(for: pos)
if previousRect != CGRect.zero {
if currentRect.origin.y > previousRect.origin.y {
// Array of Strings
var currentLines = textView.text.components(separatedBy: "\n")
// Remove Blank Strings
currentLines = currentLines.filter{ $0 != "" }
//increase the counter counting how many items inside the array
counter = currentLines.count
}
}
previousRect = currentRect
}
这篇关于Swift 3 - 在 UITextView 中检测新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文