Reputation: 441
Have a UITextView that is submitting character input through the "Send" Button on the keyboard. I have tried all of these below, yet it still makes it through with no characters.
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
}
I have tried these and more...
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") means "Send" button has been pressed
2.) if(textView.text != "") checking if textView is null
The textView is null but still makes it through the if statements I have tried above.
Upvotes: 2
Views: 311
Reputation: 24185
To get the new text length you need to use the range and text parameter values as the following:
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
?.
Upvotes: 2