检测新行在UITextView中启动的时刻 [英] Detect moment when newline starts in UITextView

查看:108
本文介绍了检测新行在UITextView中启动的时刻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在UITextView中检测托架何时进入新行。我可以通过比较总后期宽度与UITextView宽度来检测它:

I try to detect when carriage goes at new line in UITextView. I can detect it by comparison total later width with UITextView width:

CGSize size = [textView.text sizeWithAttributes:textView.typingAttributes];
if(size.width > textView.bounds.size.width)
      NSLog (@"New line");

但它无法正常工作,因为 -sizeWithAttributes:textView 仅返回没有缩进宽度的字母宽度。请帮忙解决这个问题。

But it dose not work proper way because -sizeWithAttributes:textView returns only width of letters without indentation width. Help please solve this.

推荐答案

我会这样做:


  • 获取最后一个字符的 UITextPosition

  • 调用 caretRectForPosition UITextView 上的

  • 创建 CGRect 变量并且最初在其中存储 CGRectZero

  • textViewDidChange中:方法,通过传递 UITextPosition 来调用 caretRectForPosition:

  • 将其与存储在 CGRect 变量中的当前值。如果caretRect的新y原点大于最后一个,则表示已达到新行。

  • Get the UITextPosition of the last character.
  • Call caretRectForPosition on your UITextView.
  • Create a CGRect variable and initially store CGRectZero in it.
  • In your textViewDidChange: method, call caretRectForPosition: by passing the UITextPosition.
  • Compare it with the current value stored in the CGRect variable. If the new y-origin of the caretRect is greater than the last one, it means a new line has been reached.

示例代码:

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

    UITextPosition* pos = yourTextView.endOfDocument;//explore others like beginningOfDocument if you want to customize the behaviour
    CGRect currentRect = [yourTextView caretRectForPosition:pos];

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

}

另外,你应该阅读<$ c $的文档c> UITextInput 协议参考此处。这是神奇的,我告诉你。

Also, you should read the documentation for UITextInput protocol reference here. It is magical, I'm telling you.

如果您对此有任何其他问题,请告诉我。

Let me know if you have any other issues with this.

这篇关于检测新行在UITextView中启动的时刻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆