Reputation: 1271
I have a UITextView
a user can enter a lot of text into (approx 500 characters).
I'd like to prevent the user being able to submit the form if for example it is just full of empty, new lines.
I tried adding this -
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else { return false }
return true
}
Which prevented them simply hitting return over and over, but it also stops the text wrapping.
How can I either strip the text body so multiple new lines are removed or prevent them in the first place?
Upvotes: 3
Views: 747
Reputation: 4391
When the textfield is finished editing, or will be submitted, you can remove all whitespace and newline characters like this, using CharacterSet
:
let myString = " Hello world "
let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
This will remove the spaces around Hello World but not the one in the middle.
All you have to do is check that the text is not equal to an empty string with textView.text != ""
before using the data.
Upvotes: 1