IOS UITextField &UITextView
UITextField
限制textField长度
曾经,以为输入框只是输入字符的,但真的认真为一个登陆界面输入框而改了六七次以后,发现好烦人啊,先谢谢测试的不厌其烦,不杀之恩,不想再用IOS的输入框就是这样子的来敷衍产品汪,认真思考了一下,还真有点不好搞啊,于是呼,找了点测试过能用的代码,贴这里给我们这些菜鸟用,万恶的复制啊,你ctrl v一下,不带走一片云彩。
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
name:@"UITextFieldTextDidChangeNotification"
object:self.textField];
#define kMaxLength 10
-(void)textFiledEditChanged:(NSNotification *)obj{
[self setNeedsStatusBarAppearanceUpdate];
UITextField *textField = (UITextField *)obj.object;
NSString *toBeString = textField.text;
NSString *lang = [[[UITextInputMode activeInputModes] firstObject]primaryLanguage]; // 键盘输入模式
if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [textField markedTextRange];
//获取高亮部分
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
if (toBeString.length > kMaxLength) {
textField.text = [toBeString substringToIndex:kMaxLength];
}
}
// 有高亮选择的字符串,则暂不对文字进行统计和限制
else{
}
}
// 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
else{
if (toBeString.length > kMaxLength) {
textField.text = [toBeString substringToIndex:kMaxLength];
}
}
}
UITextView
限制textView长度
这个代码着实有点长啊,不过都包含了中,英文字符输入时限制,而且带emoji时截取显示半个或乱码字符也处理一下,看着挺强大了,万恶的复制啊,都别那么懒了,附上原文链接,想研究的,可以去看看http://blog.csdn.net/fengsh998/article/details/45421107。
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
UITextRange *selectedRange = [textView markedTextRange];
//获取高亮部分
UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
//获取高亮部分内容
//NSString * selectedtext = [textView textInRange:selectedRange];
//如果有高亮且当前字数开始位置小于最大限制时允许输入
if (selectedRange && pos) {
NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
if (offsetRange.location < MAX_LIMIT_NUMS) {
return YES;
}
else
{
return NO;
}
}
NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;
if (caninputlen >= 0)
{
return YES;
}
else
{
NSInteger len = text.length + caninputlen;
//防止当text.length + caninputlen < 0时,使得rg.length为一个非法最大正数出错
NSRange rg = {0,MAX(len,0)};
if (rg.length > 0)
{
NSString *s = @"";
//判断是否只普通的字符或asc码(对于中文和表情返回NO)
BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
if (asc) {
s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
}
else
{
__block NSInteger idx = 0;
__block NSString *trimString = @"";//截取出的字串
//使用字符串遍历,这个方法能准确知道每个emoji是占一个unicode还是两个
[text enumerateSubstringsInRange:NSMakeRange(0, [text length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
if (idx >= rg.length) {
*stop = YES; //取出所需要就break,提高效率
return ;
}
trimString = [trimString stringByAppendingString:substring];
idx++;
}];
s = trimString;
}
//rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
[textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
//既然是超出部分截取了,哪一定是最大限制了。
// self.textField.text = [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS];
}
return NO;
}
}
- (void)textViewDidChange:(UITextView *)textView
{
UITextRange *selectedRange = [textView markedTextRange];
//获取高亮部分
UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
//如果在变化中是高亮部分在变,就不要计算字符了
if (selectedRange && pos) {
return;
}
NSString *nsTextContent = textView.text;
NSInteger existTextNum = nsTextContent.length;
if (existTextNum > MAX_LIMIT_NUMS)
{
//截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)
NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
[textView setText:s];
}
//不让显示负数 口口日
// self.textField.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS];
}
UITextView的动态适应高度处理
- (CGSize)getStringRectInTextView:(NSString *)string InTextView:(UITextView *)textView;
{
//
// NSLog(@"行高 = %f container = %@,xxx = %f",self.textview.font.lineHeight,self.textview.textContainer,self.textview.textContainer.lineFragmentPadding);
//
//实际textView显示时我们设定的宽
CGFloat contentWidth = CGRectGetWidth(textView.frame);
//但事实上内容需要除去显示的边框值
CGFloat broadWith = (textView.contentInset.left + textView.contentInset.right
+ textView.textContainerInset.left
+ textView.textContainerInset.right
+ textView.textContainer.lineFragmentPadding/*左边距*/
+ textView.textContainer.lineFragmentPadding/*右边距*/);
CGFloat broadHeight = (textView.contentInset.top
+ textView.contentInset.bottom
+ textView.textContainerInset.top
+ textView.textContainerInset.bottom);//+self.textview.textContainer.lineFragmentPadding/*top*//*+theTextView.textContainer.lineFragmentPadding*//*there is no bottom padding*/);
//由于求的是普通字符串产生的Rect来适应textView的宽
contentWidth -= broadWith;
CGSize InSize = CGSizeMake(contentWidth, MAXFLOAT);
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineBreakMode = textView.textContainer.lineBreakMode;
NSDictionary *dic = @{NSFontAttributeName:textView.font, NSParagraphStyleAttributeName:[paragraphStyle copy]};
CGSize calculatedSize = [string boundingRectWithSize:InSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
CGSize adjustedSize = CGSizeMake(ceilf(calculatedSize.width),calculatedSize.height + broadHeight);//ceilf(calculatedSize.height)
return adjustedSize;
}
- (void)refreshTextViewSize:(UITextView *)textView
{
CGSize size = [self getStringRectInTextView:textView.text InTextView:textView];//[textView sizeThatFits:CGSizeMake(CGRectGetWidth(textView.frame), MAXFLOAT)];
if (self.autoAdpterRect && (size.height > CGRectGetHeight(textView.frame)))
{
CGRect frame = textView.frame;
frame.size.height = size.height;
textView.frame = frame;
}
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
//对于退格删除键开放限制
if (text.length == 0) {
return YES;
}
UITextRange *selectedRange = [textView markedTextRange];
//获取高亮部分
UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
//获取高亮部分内容
//NSString * selectedtext = [textView textInRange:selectedRange];
//如果有高亮且当前字数开始位置小于最大限制时允许输入
if (selectedRange && pos) {
NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
if (offsetRange.location < MAX_LIMIT_NUMS) {
return YES;
}
else
{
return NO;
}
}
NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;
if (caninputlen >= 0)
{
//加入动态计算高度
CGSize size = [self getStringRectInTextView:comcatstr InTextView:textView];
CGRect frame = textView.frame;
frame.size.height = size.height;
textView.frame = frame;
return YES;
}
else
{
NSInteger len = text.length + caninputlen;
//防止当text.length + caninputlen < 0时,使得rg.length为一个非法最大正数出错
NSRange rg = {0,MAX(len,0)};
if (rg.length > 0)
{
NSString *s = @"";
//判断是否只普通的字符或asc码(对于中文和表情返回NO)
BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
if (asc) {
s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
}
else
{
__block NSInteger idx = 0;
__block NSString *trimString = @"";//截取出的字串
//使用字符串遍历,这个方法能准确知道每个emoji是占一个unicode还是两个
[text enumerateSubstringsInRange:NSMakeRange(0, [text length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
NSInteger steplen = substring.length;
if (idx >= rg.length) {
*stop = YES; //取出所需要就break,提高效率
return ;
}
trimString = [trimString stringByAppendingString:substring];
idx = idx + steplen;
}];
s = trimString;
}
//rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
[textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
//由于后面反回的是NO不触发didchange
[self refreshTextViewSize:textView];
//既然是超出部分截取了,哪一定是最大限制了。
self.lbNums.text = [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS];
}
return NO;
}
}
- (void)textViewDidChange:(UITextView *)textView
{
UITextRange *selectedRange = [textView markedTextRange];
//获取高亮部分
UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
//如果在变化中是高亮部分在变,就不要计算字符了
if (selectedRange && pos) {
return;
}
NSString *nsTextContent = textView.text;
NSInteger existTextNum = nsTextContent.length;
if (existTextNum > MAX_LIMIT_NUMS)
{
//截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)
NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
[textView setText:s];
}
//不让显示负数 口口日
self.lbNums.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS];
[self refreshTextViewSize:textView];
}
公用方法
stringByReplacingCharactersInRange: withString:
實現字符串删除,替换
NSString *str = @"1234567890";
[str stringByReplacingCharactersInRange:NSMakeRange(str.length-1, 1) withString:@""];
NSLog(@"str = %@", str); // str = 123456789
[str stringByReplacingCharactersInRange:NSMakeRange(str.length-1, 1) withString:@"1"];
解释:NSMakeRange(str.length-1, 1),将字符串str定位到第九个字符即‘9’,取长度为1的字符串,即9后第一个字符串 ‘0’,用字符串@“”替代‘0’,即所得的结果为“123456789”