代码之家  ›  专栏  ›  技术社区  ›  husharoonie

UITextView。我无法使用键盘发送Swift

  •  2
  • husharoonie  · 技术社区  · 8 年前

    有一个 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.) 如果(文本=“\n”) 表示已按下“发送”按钮

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

    textView为null,但仍能通过我在上面尝试过的if语句。

    1 回复  |  直到 8 年前
        1
  •  2
  •   hasan    8 年前

    要获取新的文本长度,需要使用范围和文本参数值,如下所示:

    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
    }
    

    详细信息: shouldChangeTextIn在 UITextView。这是有道理的,因为 在该功能中决定应用更改 shouldChangeTextIn ?。