ios - UITextView .isEmpty 不适用于键盘发送 Swift

标签 ios swift uitextview

有一个通过键盘上的“发送”按钮提交字符输入的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/

相关文章:

ios - 为什么实例变量在闭包内具有不同的值?

ios - 在 UITextView 更改时更改 UIReturnKeyType

ios - 为非 gailbreak 设备中已安装的应用下载和安装 .IPA 文件(开发应用商店)

ios - 如何使用 SWRevealViewController 显示调整后的侧边栏?

ios - 使用具有神奇记录的多个键进行排序时找不到键路径

ios - 初始化 CBCentralManager : Type of expression is ambiguous without more context

swift - 使用异步搜索结果重新加载表

ios - 如何在swift中通过单元格解析json纬度和经度

ios - 编辑 TextView 属性

swift - UITextView 文本从中间而不是顶部开始