func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if range.length + range.location > commentView.text!.count{
return false
}
let newLength = (commentView.text?.count)! + text.count - range.length
let i = charCount - newLength
if i < 30 {
charCountLabel.textColor = UIColor.red
} else {
charCountLabel.textColor = UIColor(r: 79, g: 79, b: 79)
}
charCountLabel.text = "\(i)"
return newLength < charCount
}
上面的代码是UITextView的字符计数器,但是当我在UITextView中输入单个表情符号时,编辑停止了,为什么呢?以及如何整合修复
CommentView:UItextView charCount:Int charCountLabel:UIlabel
当我尝试发送另一个角色时,通过线程踩到我得到了这个:
修改
在通过调试器后,我发现第二个表情符号或任何字符都会导致&#34; I&#34; var是一些与#34; newLength&#34;相同的超长数字。 ......有没有人有任何想法?
答案 0 :(得分:0)
我尝试在测试项目中运行您的代码并遇到了几个问题。我假设您初始化'charCount'时开始为0,但是当您键入第一个字符时,这会导致'i'为-1,然后在每个字符后返回false。
如果您只是尝试实现文本长度计数器,则可以使用更简单的方法。在添加/删除常规文本和表情符号字符时,以下两种方法会在计数器标签中填充正确的字符数。
我尝试的第一个方法是实现textView委托func textViewDidChange(_ textView:UITextView)。这将在您键入的每个字符后更新标签计数。如果需要,您还可以在此处设置文本颜色。
func textViewDidChange(_ textView: UITextView) {
// only want to update character count label for commentView
guard textView == commentView, let string = textView.text else {
return
}
// update counter label text with the current text count of the textview
charCountLabel.text = "\(string.count)"
}
第二种方法是使用您正在使用的textView委托。这是我在测试项目中工作的一些代码。可能有更好的方法,但这会让你前进。
@IBOutlet weak var commentView: UITextView!
@IBOutlet weak var charCountLabel: UILabel!
let minCount = 30
let maxCount = 120
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// only want to update character count label for commentView
guard textView == commentView, let string = textView.text else {
return true
}
// get current text + new character being entered
var newStr = string+text
// check if this is a backspace
let isDeleting = (range.length > 0) && text.isEmpty
if isDeleting == true {
// trim last character
// you may want to drop based on the range.length, however you'll need
// to determine if the character is an emoji and adjust the number of characters
// as range.length returns a length > 1 for emojis
newStr = String(newStr.dropLast())
}
// set text color based on whether we're over the min count
charCountLabel.textColor = newStr.count < minCount ? .red : .blue
// set the character count in the counter label
charCountLabel.text = "\(newStr.count)"
// if we're less than the max count allowed, return true
return newStr.count < maxCount
}