您的位置:首页 > 移动开发 > IOS开发

iOS【textView或者textField文本输入字数限制】

2015-07-08 15:24 513 查看
【textView文本输入 字数限制】

// 监听文本改变 触发时机(通过发送通知完成)

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

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

NSAttributedString *toBeString = textView.attributedText;

// NSLog(@" - -%@",[_contentView.textInputMode primaryLanguage]);

//方法已经不推荐使用了,直接获取textinputMode时表情键盘不会响应

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

if (toBeString.length > MAXLenth)//MAXLenth定义的宏

{

[self showHUDWithText:@"输入字数限制300"];

}

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

UITextRange *selectedRange = [textView markedTextRange];

//获取高亮部分

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

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

if (!position) {

if (toBeString.length >= MAXLenth) {

textView.attributedText = [toBeString attributedSubstringFromRange:NSMakeRange(0, MAXLenth)];

textView.font = [UIFont systemFontOfSize:14.f];

}

if (textView.attributedText.length > 300)

{

self.lenthLabel.text = @"已输入字数:300";

}

else self.lenthLabel.text = [NSString stringWithFormat:@"已输入字数:%@",@(textView.attributedText.length)];

}

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

else{

}

}

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

else{

if (toBeString.length > MAXLenth) {

textView.attributedText = [toBeString attributedSubstringFromRange:NSMakeRange(0, MAXLenth)];

textView.font = [UIFont systemFontOfSize:14.f];

}

if (textView.attributedText.length > 300)

{

self.lenthLabel.text = @"已输入字数:300";

}

else self.lenthLabel.text = [NSString stringWithFormat:@"已输入字数:%@",@(textView.attributedText.length)];

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: