限制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];
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];
}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];
}