I have a UITextView and I do not want the user to have any spaces in the text typed. What should I do to not allow him to use the space button? Thanks!
You need to
Specify the view controller as the delegate to your text view (you can do this either programmatically or specify the delegate in Interface Builder); and
Your UITextViewDelegate method shouldChangeTextInRange needs to check to see if the string to be inserted contains a space:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if ([text rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].location != NSNotFound) {
return NO;
}
return YES;
}
Or, in Swift:
extension ViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
return text.rangeOfCharacter(from: .whitespacesAndNewlines) == nil
}
}
Note, this is not checking to see if the replacementText is equal to space, because that is an insufficient check. Instead, this is checking whether a space occurs anywhere inside the replacement text. This is an important distinction because it's possible to paste text into the text view that might not be equal to a space, but might contain a space somewhere in the pasted value.
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