转自:http://www.cnblogs.com/niexiaobo/p/4597958.html
当调用系统键盘输入时,预输入,会奔溃,当调用以下的方法时,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
@property (nonatomic, strong) UITextField *txtName;
- (void)viewDidLoad {
[super viewDidLoad];
//UIControlEventEditingChanged(包括中文和英文等输入法)
[self.txtName addTarget:self action:@selector(limitLength:) forControlEvents:UIControlEventEditingChanged];
}
//包括中文和英文等输入法判断,不然会因为联想记忆而崩溃
-(void)limitLength:(UITextField *)sender
{
bool isChinese;//判断当前输入法是否是中文
if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString: @"en-US"]) {
isChinese = false;
}
else
{
isChinese = true;
}
if(sender == self.txtName) {
// 8位
NSString *str = [[self.txtName text] stringByReplacingOccurrencesOfString:@"?" withString:@""];
if (isChinese) { //中文输入法下
UITextRange *selectedRange = [self.txtName markedTextRange];
//获取高亮部分
UITextPosition *position = [self.txtName positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
NSLog(@"汉字");
if ( str.length>=9) {
NSString *strNew = [NSString stringWithString:str];
[self.txtName setText:[strNew substringToIndex:8]];
}
}
else
{
NSLog(@"输入的英文还没有转化为汉字的状态");
}
}else{
NSLog(@"str=%@; 本次长度=%d",str,[str length]);
if ([str length]>=9) {
NSString *strNew = [NSString stringWithString:str];
[self.txtName setText:[strNew substringToIndex:8]];
}
}
}
}