I have a ViewController
with a UITextView
and a "Send" bar button item in the navigation bar which submits the text in the textView. Since the UITextView does not support placeholder text like the UITextField, I am handling it on my own with the following code which resides in the UITextViewDelegate
method, shouldChangeTextInRange
.
Note: The following code I wrote so far enables the Send button for whitespace/newline characters too. But this is what I need help with:
How can I disable the Send button when the textView contains only whitespace or newline characters but enable it otherwise while also setting/clearing the placeholder text appropriately?
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
// Combine the postTextView text and the replacement text to
// create the updated text string
let currentText : NSString = textView.text
let updatedText = currentText.stringByReplacingCharactersInRange(range, withString:text)
// If the updated textView text will be empty, disable the send button,
// set the placeholder text and color, and set the cursor to the beginning of the text view
if updatedText.isEmpty {
sendBarButton.enabled = false
textView.text = "Write something..."
textView.textColor = UIColor.lightGrayColor()
textView.selectedTextRange = textView.textRangeFromPosition(textView.beginningOfDocument, toPosition: textView.beginningOfDocument)
return false
}
// If the textView's placeholder is showing (i.e.: the textColor is light gray for placeholder text)
// and the length of the replacement string is greater than 0,
// clear the text view and set its color to black to prepare for the user to enter text
else if (textView.textColor == UIColor.lightGrayColor() && !(text.isEmpty)) {
sendBarButton.enabled = true
textView.text = nil
textView.textColor = UIColor.blackColor()
}
return true
}
UPDATE: I understand the following code may be used to trim/recognize whitespace and newline characters, but not sure how to apply it here in this case: stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
Thanks for your help.