UITextView和UITextField字数输入控制

上代码code

UITextViewci

//每次TextView输入或删除的时候都会调用这个协议方法   <UITextViewDelegate>
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    //用指定的字符串替换字符串,返回新的字符串
    NSString * new = [textView.text stringByReplacingCharactersInRange:range withString:text ];
    //保证新建通知的内容输入框最多只能输入4个字
    NSInteger res = 4 - new.length;
    if (res >= 0) {
        return YES;
    }else{
        return NO;
    }
}

可是这个方法若是输入是中文或者是联想词的时候都会出现问题,这是由于这个方法字符串

    NSString * new = [textView.text stringByReplacingCharactersInRange:range withString:text ];

不识别中文以及联想词。get

在加一个这个就能够了input

-(void)textViewDidChange:(UITextView *)textView
{
    //若是是联想词的话下面 shouldChange。。。这个方法会没法识别
    if (textView.text.length > 4) {
        textView.text = [textView.text substringToIndex:4];
    }


UITextFieldstring

#pragma mark - textField Delegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *new = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSInteger res = 4 - new.length;
    if (res >= 0) {
        return YES;
    }else{
        return NO;
    }
}

//一样会有相同问题须要在加一个方法
[_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

//shouldChangeCharacter不是识别中文和联想字因此在加一个这个,这个方法是本身写的,不是协议里已有的方法。
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.inputTxt) {
        if (textField.text.length > 4) {
            textField.text = [textField.text substringToIndex:4];
        }
    }
}

其实就是两个方法很简单。it

相关文章
相关标签/搜索