UITextfield

- (void)viewDidLoad {

    [super viewDidLoad];

//    self.m_renameType = ClearRenameTypeNone;

    // Do any additional setup after loading the view.

    [selfinitUI];

    [self.view setBackgroundColor:[UIColor whiteColor]];



    //添加代理

    //self.m_newnameEdit.delegate = self;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:self.m_newnameEdit];

}

-(void)dealloc{

//    if(self.m_newnameEdit != nil){

//        self.m_newnameEdit.delegate = nil;

//    }

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:self.m_newnameEdit];

}



-(void)textFiledEditChanged:(NSNotification*)obj{

    UITextField*textField = (UITextField*)obj.object;

    NSString*toBeString = textField.text;

    NSString*lang = [[textFieldtextInputMode]primaryLanguage];// 获取当前键盘输入模式

    NSLog(@"%@",lang);



    if([lang isEqualToString:@"zh-Hans"]) {//简体中文输入,第三方输入法(搜狗)所有模式下都会显示“zh-Hans”

        UITextRange*selectedRange = [textFieldmarkedTextRange];

        //获取高亮部分

        UITextPosition*position = [textFieldpositionFromPosition:selectedRange.startoffset:0];

        //没有高亮选择的字,则对已输入的文字进行字数统计和限制

            if(!position) {

                NSString*getStr = [selfgetSubString:toBeString];

                if(getStr && getStr.length>0) {

                    textField.text= getStr;

                }

            }

    }else{

        NSString*getStr = [selfgetSubString:toBeString];

        if(getStr && getStr.length>0) {

            textField.text= getStr;

        }

    }

}

- (NSString*)getSubString:(NSString*)string{

    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);

    NSData* data = [stringdataUsingEncoding:encoding];

    NSIntegerlength = [datalength];

    if(length >15) {

        //self.m_newnameEdit.enabled = NO;

        NSData*data1 = [datasubdataWithRange:NSMakeRange(0,15)];

        NSString*content = [[NSStringalloc]initWithData:data1encoding:encoding];

        //当截取kMaxLength长度字符时把中文字符截断返回的content会是nil

        if(!content || content.length==0) {

            data1 = [datasubdataWithRange:NSMakeRange(0,15-1)];

            content = [[NSStringalloc]initWithData:data1encoding:encoding];

        }

        returncontent;

    }

    return nil;

}

你可能感兴趣的:(UITextfield)