[英]Prevent non-ASCII characters from being captured in a UITextView
我有一个旧数据库列,仅支持ASCII字符集。 我需要一种防止将非ASCII字符键入或粘贴到UITextView中的方法。 我需要过滤掉表情符号和所有其他unicode字符。
这有两个部分。 首先,通过适当设置键盘类型来防止首先键入非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;
}
这就是我用于UITextField的方法,只是替代解决方案,它可以在默认以及自定义键盘上运行,并禁用表情符号的复制粘贴。 无需将键盘类型设置为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
}
Swift 4干净代码解决方案
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return string.canBeConverted(to: .ascii)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.