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

相關文章
相關標籤/搜索