在在网上查了资料,�很多都是下面这个方法,但是在原生键盘上是有问题的,当当在手机上英文九宫格连点的时候,会替换掉最后的文字
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:)
name:@"UITextFieldTextDidChangeNotification" object:myTextField];
-(void)textFieldEditChanged:(NSNotification *)obj
{
UITextField *textField = (UITextField *)obj.object;
NSString *toBeString = textField.text;
NSString *lang = [textField.textInputMode primaryLanguage];
if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
{
//获取高亮部分
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position)
{
if (toBeString.length > MAX_STARWORDS_LENGTH)
{
textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
}
}
}
// 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
else
{
if (toBeString.length > MAX_STARWORDS_LENGTH)
{
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
if (rangeIndex.length == 1)
{
textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
}
else
{
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
textField.text = [toBeString substringWithRange:rangeRange];
}
}
}
}
经过多次测试后,终于解决了,首先要设置UITextField的代理,实现下面的代理方法,代码如下:
static const int nameMaxLength = 6;
@interface FCEditNameViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *nameTextField;
@property (nonatomic, strong) NSString *oldStr;//记录修改之前的值
@property (nonatomic, strong) NSString *positionStr;记录高亮的文字
@end
//当前光标位置 range.location
//已选文字长度 range.length
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string isEqualToString:@""]) {
return YES;
}
//获取高亮部分
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
if (!position) {
self.oldStr = textField.text;
if (range.length + range.location > textField.text.length) {
return NO;
}
NSInteger newStrLength = [textField.text length] + [string length] - range.length;
if (newStrLength <= nameMaxLength) {
return YES;
}else{
return NO;
}
}else{
if ([self IsChinese:string]) {
NSString *str = [NSString stringWithFormat:@"%@%@",self.oldStr,string];
self.oldStr = @"";
if (str.length > nameMaxLength) {
return NO;
}else{
return YES;
}
}
}
return YES;
}
//判断是否有中文
- (BOOL)IsChinese:(NSString *)str {
for(int i=0; i< [str length];i++){
int a = [str characterAtIndex:i];
if( a > 0x4e00 && a < 0x9fff)
{
return YES;
}
}
return NO;
}