admin管理员组

文章数量:1562603

#define MaxNumberOfDescriptionChars  50

- (void)dealloc

{

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)viewDidLoad

{

    [super viewDidLoad];


    [[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(textViewEditChanged:)name:UITextViewTextDidChangeNotification object:_titleView];

// 监听文本改变

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

    UITextView *textView = (UITextView *)obj.object;

    

    NSString *toBeString = textView.text;

    NSString *lang = [[UITextInputMode currentInputMode]primaryLanguage]; // 键盘输入模式

    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写

        UITextRange *selectedRange = [textView markedTextRange];

        //获取高亮部分

        UITextPosition *position = [textViewpositionFromPosition:selectedRange.start offset:0];

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

        if (!position) {

            if (toBeString.length > MaxNumberOfDescriptionChars) {

                textView.text = [toBeStringsubstringToIndex:MaxNumberOfDescriptionChars];

            }

        }

        // 有高亮选择的字符串,则暂不对文字进行统计和限制

        else{

            

        }

    }

    // 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况

    else{

        if (toBeString.length > MaxNumberOfDescriptionChars) {

            textView.text = [toBeStringsubstringToIndex:MaxNumberOfDescriptionChars];

        }

    }


}


//  这是个委托方法,在这里可使用可不使用。使用这个方法就是当输入的字符超过限制时就禁止输入。 

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

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

    if(new.length > MaxNumberOfDescriptionChars){

        if (![text isEqualToString:@""]) {

            return NO;

        }

    }

    return YES;

}

本文标签: 字数