限制UITextView输入字数(兼容iOS7)

限制UITextView输入字数,但是在iOS7上总是崩溃,最后查阅资料找到一下解决方法:
_numLabel是输入框后面的显示字数标签,用来显示当前输入的字数
kMaxLength是可输入的最大文字数

- ( void )textViewDidChange:( UITextView *)textView{
   
   
if (textView. text . length >= kMaxLength ) {
       
       
_numLabel . textColor = [ UIColor redColor ];
       
    }
else {
       
_numLabel . textColor = [ UIColor grayColor ];
    }

   
NSString *languageStr = [textView. textInputMode primaryLanguage ];
   
if ([languageStr isEqualToString : @"zh-Hans" ]) {
       
UITextRange *selectedRange = [textView markedTextRange ];
       
UITextPosition *position = [textView positionFromPosition :selectedRange. start offset : 0 ];
       
if (!position) {
           
if (textView. text . length >= kMaxLength ) {
               
                textView.
text = [textView. text substringToIndex : kMaxLength ];
               
_numLabel . textColor = [ UIColor redColor ];
               
            }
else {
               
               
_numLabel . textColor = UIColorFromRGB ( 0x8e8e93 );
            }
           
_numLabel . text = [ NSString stringWithFormat : @"%u/%d" , kMaxLength -textView. text . length , kMaxLength ];

        }
       
    }
else {
       
if (textView. text . length >= kMaxLength ) {
           
            textView.
text = [textView. text substringToIndex : kMaxLength ];
           
_numLabel . textColor = [ UIColor redColor ];
           
        }
else {
           
           
_numLabel . textColor = UIColorFromRGB ( 0x8e8e93 );
        }
       
       
_numLabel . text = [ NSString stringWithFormat : @"%u/%d" , kMaxLength -textView. text . length , kMaxLength ];
    }

   
   
_numLabel . text = [ NSString stringWithFormat : @"%lu/%d" ,( unsigned long )textView. text . length , kMaxLength ];

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值