//
// ViewController.m
// Project_Demo_textField
//
// Created by David on 15/1/13.
// Copyright (c) 2015年 David. All rights reserved.
//
#import "ViewController.h"
static const NSString *KnotificationName = @"UITextFieldTextDidChangeNotification";
static const int KNickNameLength = 10;
@interface ViewController ()<UITextFieldDelegate>
{
NSInteger nInputTextFieldLength;
UITextField *textField;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
textField= [[UITextField alloc] initWithFrame:CGRectMake(100,100,100, 50)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.delegate = self;
[self.view addSubview:textField];
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange:) name:(NSString *)KnotificationName object:textField];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
nInputTextFieldLength = textField.text.length;
NSLog(@"+==================%s======%ld====",__FUNCTION__,(long)nInputTextFieldLength);
return YES;
}
- (void)textFieldChange:(NSNotification *)notification
{
NSLog(@"+==============%s==========%ld====",__FUNCTION__,(long)nInputTextFieldLength);
UITextField *textFieldInput = (UITextField *)notification.object;
NSString *toBeString = textFieldInput.text;
NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [textFieldInput markedTextRange];
//获取高亮部分
UITextPosition *position = [textFieldInput positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
if ([toBeString lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > KNickNameLength) {//我们的程序是控制到10位,如果中文英文都支持10的话,改为[toBeString.length] > KNickNameLength
textFieldInput.text = [toBeString substringToIndex:nInputTextFieldLength];
}else{
nInputTextFieldLength = textFieldInput.text.length;
}
}else{// 有高亮选择的字符串,则暂不对文字进行统计和限制
// NSLog(@"===");
if ([toBeString lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > KNickNameLength) {
textFieldInput.text = [toBeString substringToIndex:nInputTextFieldLength];
}else{
nInputTextFieldLength = textFieldInput.text.length;
}
}
}else{// 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
if (toBeString.length > KNickNameLength) {
textFieldInput.text = [toBeString substringToIndex:KNickNameLength];
}else{
nInputTextFieldLength = textFieldInput.text.length;
}
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self
name:(NSString *)KnotificationName
object:textField];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end