Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not allow typing 'space' in UITextView?

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!

like image 546
Toma Radu-Petrescu Avatar asked Jan 30 '26 08:01

Toma Radu-Petrescu


1 Answers

You need to

  1. 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

  2. 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.

like image 129
Rob Avatar answered Feb 01 '26 23:02

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!