2011-02-02 24 views
5

我有一个可编辑的UITextView。现在我有一个要求,要求我查找下一行何时开始(可能是由于我点击了返回键或自动换行符)。是否有任何通知可以得出以确定下一行在打字时何时开始?UITextView(编辑) - 检测到发生下一行事件

我试图寻找解决方案来找出在textview中的光标位置,但使用selectedRange和位置属性来找出它并不能帮助我。位置值与新行之间没有任何关联。打字的位置值只是不断增加。有任何想法吗?

谢谢!

回答

2

将检测线从东西变成打“回归”,退格,以减少线路数,输入到行和单词的结尾(*注意:必须调整字体大小的变量,我建议不要使用硬编码数字,如下面的示例中所示)。

previousNumberOfLines = ((hiddenText.contentSize.height-37+21)/(21));//numbers will change according to font size 
NSLog(@"%i", previousNumberOfLines); 
10

无论何时在textView中输入新文本,都会调用以下代理。

设置委托UITextView的,那么代码如下

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; 
{ 
    if ([text isEqualToString:@"\n"]) { 
     //Do whatever you want 
    } 
    return YES; 
} 
+2

我已经使用UITextViewTextDidChangeNotification。我如何在文本中查找\ n? textView.text不会返回到目前为止输入的整个文本类型吗?一个自动换行术语包装可能已经发生,或者我可能碰到了很多空间。在这种情况下,如何检测下一行的到达? – Bourne 2011-02-02 12:24:22

+0

@bourne:是它的检测返回键 – KingofBliss 2011-02-02 12:39:26

0

为您的视图添加第二个隐藏文本视图。为可见文本视图实现shouldChangeTextInRange,并将隐藏视图上的文本设置为新文本。比较新旧文本的contentSize以检测文字换行。

0
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range 
replacementText:(NSString *)text 
{ 

    if ([text isEqualToString:@"\n"]) { 
     textView.text=[NSString stringWithFormat:@"%@\n",textView.text]; 
     // Return FALSE so that the final '\n' character doesn't get added 
     return NO; 
    } 
    // For any other character return TRUE so that the text gets added to the view 
    return YES; 
} 
0

我有点迟到了,但我也有类似的要求,有点调查后,我发现,KingofBliss的回答与

-[id<NSLayoutManagerDelegate> layoutManager:shouldBreakLineByWordBeforeCharacterAtIndex:]; 
-[id<NSLayoutManagerDelegate> layoutManager:shouldBreakLineByHyphenatingBeforeCharacterAtIndex:]; 

结合奏效了我。

您可以设置任何对象作为UITextView的布局管理器的代表,像这样:

textView.textContainer.layoutManager.delegate = (id<NSLayoutManagerDelegate>)delegate 

希望这将证明是有用的。

4

对于斯威夫特利用这个

previousRect = CGRectZero 

func textViewDidChange(textView: UITextView) { 

     var pos = textView.endOfDocument 
     var currentRect = textView.caretRectForPosition(pos) 
     if(currentRect.origin.y > previousRect?.origin.y){ 
      //new line reached, write your code 
     } 
     previousRect = currentRect 

    } 

对于目标C

CGRect previousRect = CGRectZero; 
- (void)textViewDidChange:(UITextView *)textView{ 

    UITextPosition* pos = textView.endOfDocument; 
    CGRect currentRect = [textView caretRectForPosition:pos]; 

    if (currentRect.origin.y > previousRect.origin.y){ 
      //new line reached, write your code 
     } 
    previousRect = currentRect; 

}