我有一个旧数据库列,仅支持 ASCII 字符集。我需要一种方法来防止将非 ASCII 字符键入或粘贴到 UITextView 中。我需要过滤掉表情符号和所有其他 unicode 字符。
这有两个部分。首先,通过适当设置键盘类型来防止输入非 ASCII 字符:
textView.keyboardType = UIKeyboardTypeASCIICapable;
Run Code Online (Sandbox Code Playgroud)
其次,通过实现此委托方法来防止从另一个应用程序粘贴非 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3976 次 |
| 最近记录: |