Brett Donald
Brett Donald

Reputation: 14157

Prevent non-ASCII characters from being captured in a UITextView

I have a legacy database column which only supports the ASCII character set. I need a method which prevents non-ASCII characters from being typed or pasted into a UITextView. I need to filter out emojis and all other unicode characters.

Upvotes: 1

Views: 4114

Answers (3)

matuslittva
matuslittva

Reputation: 163

Swift 4 clean code solution

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.canBeConverted(to: .ascii)
}

Upvotes: 1

Aditya Deshmane
Aditya Deshmane

Reputation: 4722

This is what I am using for UITextField, just alternative solution, this works on default as well as custom keyboards and disables copy pasting of emojis. No need to set keyboard type to ascii as it only disables emojis of default iOS keyboard.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    //This is universal solution works on default as well as custom keyboards like SwiftKeyplus it will diallow pasting emoji
    if !string.canBeConvertedToEncoding(NSASCIIStringEncoding)
    {
        return false
    }

    return true
}

Upvotes: 0

Brett Donald
Brett Donald

Reputation: 14157

There are two parts to this. Firstly, prevent non-ASCII characters from being typed in the first place by setting the keyboard type appropriately:

textView.keyboardType = UIKeyboardTypeASCIICapable;

Secondly, prevent non-ASCII characters being pasted in from another app by implementing this delegate method:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // trim any non-ASCII characters
    NSString* s = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithRange:NSMakeRange(0, 128)].invertedSet] componentsJoinedByString:@""];

    // manually replace the range in the textView
    textView.text = [textView.text stringByReplacingCharactersInRange:range withString:s];

    // prevent auto-replacement
    return NO;
}

Upvotes: 5

Related Questions