我正在尝试对我的textview进行倒计时。我的.h和.m文件设置如下。基本上,我正在寻找的是textview一个标签,当用户输入文本时,该标签从140倒数。一旦textview达到140个字符,用户就不能再输入文本了。我不确定我在这里做错了什么。任何帮助都会很棒!谢谢!
我的.h文件中的:
@interface LeaveTipViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIBarButtonItem *tipCancelButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *tipSubmitButton;
@property (weak, nonatomic) IBOutlet UITextView *tipText;
@property (weak, nonatomic) IBOutlet UILabel *countLabel;
- (IBAction)tipCancelPressed:(id)sender;
- (IBAction)tipSubmitPressed:(id)sender;
@end
我的.m文件中的:
-(void)textViewDidChange:(UITextView *)textView
{
int len = tipText.text.length;
countLabel.text=[NSString stringWithFormat:@"%i",140-len];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
BOOL flag = NO;
if([text length] == 0)
{
if([tipText.text length] != 0)
{
flag = YES;
return YES;
}
else {
return NO;
}
}
else if([[tipText text] length] > 139)
{
return NO;
}
return YES;
}
答案 0 :(得分:4)
只需将此方法更改为
即可-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
return textView.text.length + (text.length - range.length) <= 140;
}
答案 1 :(得分:3)
在决定是否允许编辑之前,您需要计算编辑完成后存在的实际文本:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSString *resultingText = [textView.text stringByReplacingCharactersInRange:range withString:text];
return ([resultingText length] <= 140);
}
答案 2 :(得分:2)
添加到您的viewController接口LeaveTipViewController:UIViewController
设置self.tipText.delegate = self
并使用这两种方法
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSUInteger newLength = [textView.text length] + [text length] - range.length;
return (newLength > 140) ? NO : YES;
}
-(void)textViewDidChange:(UITextView *)textView
{
int maxChars = 140;
int charsLeft = maxChars - [textView.text length];
if(charsLeft == 0) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"No more characters"
message:[NSString stringWithFormat:@"You have reached the character limit of %d.",maxChars]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alert show];
}
self.lblLettersCount.text = [NSString stringWithFormat:@"%d characters left",charsLeft];
}
答案 3 :(得分:1)
您可以使用以下代码检查并获取字符数:
- (void)textViewDidChange:(UITextView *)textView{
NSInteger maxLength = 140;
NSString *text = textView.text;
if([[textView text] length] > maxLength )
{
textView.text = [text substringToIndex:[text length]-1];
}
}