限制uitextview中的字符数 [英] Limit number of characters in uitextview
问题描述
我提供了一个文本视图来推特一些字符串。
我正在应用以下方法将字符数限制为140个。
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if([text isEqualToString:@\ b]){
DLog(@Ohoooo);
返回YES;
}否则if([[textView text] length]> 140){
返回NO;
}
返回YES;
}
除了退格不起作用的第一个条件外,代码运行良好。
假设我已达到140个字符的限制,因此该方法将给我假,用户无法插入更多字符,但在此之后,当我尝试删除某些字符时,文本视图的行为与禁用时一样。 / p>
那么问题是如何从 textview.text
中删除字符或重新启用文本视图。
你应该寻找一个空字符串,作为 apple reference 说
如果用户按下Delete键,则范围的长度为1,空字符串对象将替换该单个字符。
I认为你实际想要的支票是 [[textView text] length] - range.length + text.length> 140
,用于计算剪切/粘贴操作。
I am giving a text view to tweet some string .
I am applying the following method to restrict the number of characters to 140 in length.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if([text isEqualToString:@"\b"]){
DLog(@"Ohoooo");
return YES;
}else if([[textView text] length] > 140){
return NO;
}
return YES;
}
The code is working nicely except the first condition that backspace is not working. suppose that I have reached the limit of 140 characters so that the method will give me false and the user can not insert more characters but after that when I try to delete some characters the text view behave as it is disabled .
So the question how do delete characters from textview.text
or re-enable the text view .
You should be looking for an empty string instead, as the apple reference says
If the user presses the Delete key, the length of the range is 1 and an empty string object replaces that single character.
I think the check you actually want to make is something like [[textView text] length] - range.length + text.length > 140
, to account for cut/paste operations.
这篇关于限制uitextview中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!