我有一个只支持ASCII字符集的旧数据库列。我需要一种方法来防止非ASCII字符被输入或粘贴到UITextView中。我需要过滤掉表情符号和所有其他unicode字符。
答案 0 :(得分:3)
这有两个部分。首先,通过适当设置键盘类型,首先防止输入非ASCII字符:
textView.keyboardType = UIKeyboardTypeASCIICapable;
其次,通过实现此委托方法阻止从其他应用程序粘贴非ASCII字符:
- (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;
}
答案 1 :(得分:0)
我正在使用的UITextField,只是替代解决方案,这适用于默认和自定义键盘,并禁用复制粘贴emojis。无需将键盘类型设置为ascii,因为它只会禁用默认iOS键盘的表情符号。
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
}
答案 2 :(得分:0)
迅速4 干净代码解决方案
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return string.canBeConverted(to: .ascii)
}