【问题标题】:Detect uitextview empty line检测uitextview空行
【发布时间】:2012-10-07 18:03:29
【问题描述】:

我有两个UITextView,让用户在第一个文本视图中输入一些文本,并在第二个文本视图中产生一些不同的文本。

用户可以在第一个文本视图中输入下一行,但是我不希望在第二个文本视图中生成空行。我想知道如何检测第一个文本视图中是否有空行并删除这些行?

谢谢。

字符输入计数错误的结果:

-(void)textViewDidChange:(UITextView *)textView{

if ([inputTextSection.text rangeOfString:@"\n\n"].location == NSNotFound) return;
NSString *resultStr = [inputTextSection.text stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"];
inputTextSection.text = resultStr;


 int maxChars = 70; //maximum characters
 int charsLeft = maxChars - [inputTextSection.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];
    [alert release];
}

liveCountTextView.text = [NSString stringWithFormat:@"%d/70",charsLeft];}

【问题讨论】:

  • 用 '\n' 尝试一些实验。
  • 你见过一些 NSString 方法,比如 [str componentsSeparatedByString:@","];
  • @ArpitParekh 你能解释一下吗?我怎样才能将代码暗示到我的案例中?谢谢

标签: objective-c uitextview


【解决方案1】:
  1. 您应该设置第一个UITextViewdelegate
  2. 在文本视图委托中实现上述方法:

    - (void)textViewDidChange:(UITextView *)textView
    {
        if ([textView.text rangeOfString:@"\n\n"].location == NSNotFound) return;
        NSString *resultStr = [textView.text stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"];
        textView.text = resultStr;
    }
    

这将删除所有空行。

【讨论】:

  • 这就是我要找的,非常感谢!然而,我很抱歉!我没有足够的声望投票给你的答案。
  • 在这里实现字符计数时,我遇到了一个关于代码的新问题。该脚本可以进行计数或执行此清除空行方法。我想知道如何编写代码来结合这两种方法?请看一下我编辑的问题,非常感谢!
  • 嗯。有什么问题?顺便把if(charsLeft == 0)换成if(charsLeft <= 0)
  • 我只能使任何一个参数起作用。在上面的脚本中,liveCountTextView.text 有效,但是您的脚本不起作用。如果我只是使用你的脚本,它会完美运行。
  • @zeropt7 在方法的开头添加这一行:if (textView != inputTextSection) return;
猜你喜欢
  • 2012-03-04
  • 2017-06-01
  • 1970-01-01
  • 2016-07-07
  • 2012-12-07
  • 2018-07-23
  • 1970-01-01
  • 2013-11-29
  • 2011-06-19
相关资源
最近更新 更多