有一个通过键盘上的“发送”按钮提交字符输入的UITextView。我已经尝试了下面所有这些,但它仍然能够在没有字符的情况下完成。
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text == "\n") {
if(textView.text != "" || !textView.text.isEmpty){
print("still printing")
//**I dont want it to make it here but it does with no characters in textView after clicking send on keyBoard
//It still makes it here when send button is pressed and textView is null.
return false
}
}
return true
}
我已经尝试过这些以及更多...
if(textView.text != "" || !textView.text.isEmpty || textView.text == nil)
if textView!.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty {
[...]
}
if (self.textView.text.characters.count > 0) { }
1.) if (text == "\n") 表示已按下“发送”按钮
2.) if(textView.text != "") 检查textView是否为空
textView 为空,但仍然通过我上面尝试过的 if 语句。
最佳答案
要获取新的文本长度,您需要使用范围和文本参数值,如下所示:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let insertedText = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if insertedText.count == 1 {
textView.text = insertedText
}
return false
}
Details: The shouldChangeTextIn is triggered before the text change on the UITextView. That makes sense because the decision for applying the change is taken in this function
shouldChangeTextIn
?.
关于ios - UITextView .isEmpty 不适用于键盘发送 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49250992/