输入输限制字数

简介: <p style="padding-top:0px; padding-bottom:0px; margin-top:0px; margin-bottom:10px; clear:both; height:auto; overflow:hidden; font-size:14px; line-height:28px; color:rgb(95,101,108); font-family:'H

#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;

}

目录
相关文章
|
1月前
|
C++
58C++的输入和输出
58C++的输入和输出
10 0
|
1月前
|
C语言
输入&输出
【2月更文挑战第13天】输入&输出。
11 1
|
8月前
|
存储
I/O输入和输出详解
I/O输入和输出详解
|
9月前
|
编译器 C语言 C++
scanf的多组输入及两种输入方法你还不会嘛?看完这篇文章让你彻底认识scanf!
scanf的多组输入及两种输入方法你还不会嘛?看完这篇文章让你彻底认识scanf!
197 0
|
6月前
|
编译器 C语言
C 输入 & 输出
C 输入 & 输出。
75 1
|
12月前
|
存储 程序员 C++
C++ 中的基本输入/输出
C++ 附带的库为我们提供了许多执行输入和输出的方法。在 C++ 中,输入和输出以字节序列或更通常称为流的形式执行。
101 0
|
JavaScript
input 每输入一次都会失去焦点需要再次点击才能输入
出现上述问题其实就是遍历的时候key值绑定的不合理
226 0
|
存储 监控 C++
C++ 输入的是1.3变1.29999995问题
C++ 输入的是1.3变1.29999995问题
C++ 输入的是1.3变1.29999995问题
|
数据格式
在文本框中输入两个操作数和选择运算符后,在页面上显示输出结果
在文本框中输入两个操作数和选择运算符后,在页面上显示输出结果
369 0
在文本框中输入两个操作数和选择运算符后,在页面上显示输出结果

热门文章

最新文章