I wonder how I proper check if a uitextview is empty.
Right now I have a validation fucntion which does the check:
if let descText = myTextView.text {
if descText.isEmpty {
descErrorLabel.isHidden = false
} else {
descErrorLabel.isHidden = true
}
}
It this enough to prevent the user from sending an empty textview or must I check of whitespaces also, something like:
stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
Basic Swift Code for iOS Apps Follow the below steps. Step 2 − Open Main. storyboard add one textField, one button and one label one below other as shown in the figure. On click of the button we will check whether the text field is empty or not and show the result in label.
text is nil. So, when there is no text, field. text == nil , doing field.
To check if string is empty in Swift, use the String property String. isEmpty . isEmpty property is a boolean value that is True if there are no any character in the String, or False if there is at least one character in the String.
If you have a text field, you normally want a user to enter in something into the text field. So Java allows us to check if a text field is empty or not through the isEmpty() function. You can then do anything after this including prompt the user to enter in something or whatever.
You could roll it all up into something like this...
func validate(textView textView: UITextView) -> Bool {
guard let text = textView.text,
!text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else {
// this will be reached if the text is nil (unlikely)
// or if the text only contains white spaces
// or no text at all
return false
}
return true
}
Then you can validate any UITextView
like...
if validate(textView: textView) {
// do something
} else {
// do something else
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With