UITextView .isEmpty 无法处理键盘发送 Swift

UITextView .isEmpty not working on keyboard send Swift

有一个 UITextView 通过键盘上的 "Send" 按钮提交字符输入。我已经尝试了下面的所有这些,但它 仍然 没有字符地通过了。

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") 表示 "Send" 按钮已被按下

2.) if(textView.text != "") 检查 textView 是否为 null

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?.