UITextField限制字数,支持iOS7

解决了iOS7上position对象总是不为nil造成判断不准的问题
- (void)nikeNameTFDidChange {

NSString *toBeString    = self.nickName.text;
// 当前输入法 - 这个判断可以去掉其实
NSString *inputLanguage = [[self.nickName textInputMode] primaryLanguage];

if([inputLanguage isEqualToString:@"zh-Hans"]){ //简体中文输入,包括简体拼音,健体五笔,简体手写
    
    //获取高亮部分
    UITextRange *selectedRange = [self.nickName markedTextRange];
    UITextPosition *position   = [self.nickName positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
    // DL修改 添加判断条件  || !selectedRange
    if (!position || !selectedRange){
        //非高亮
        [self processNickNameText:toBeString];
    }
}else{
    //中文输入法以外
    [self processNickNameText:toBeString];
}
}
- (void)processNickNameText:(NSString *)toBeString {

 if (toBeString.length > 11) {
    
    self.nickName.text = [toBeString substringToIndex:11];
    [MBProgressHUD showMessage:@"您最多只能输入11个字" toView:self.view hudConfig:nil];
}else if (toBeString.length == 11 && [self.nickName.text isEqualToString:_loginname]) {
    
    self.nickName.text = [self.nickName.text stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    [MBProgressHUD showMessage:@"您的昵称为手机号,将加密展示~" toView:self.view hudConfig:nil];
}

}

你可能感兴趣的:(UITextField限制字数,支持iOS7)