检测UITextView中的新行开始的时刻

我尝试检测何时在UITextView的新行。 我可以通过UITextView宽度比较总宽度来检测它:

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

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

这是我将如何做到这一点:

  • 获取最后一个字符的UITextPosition
  • 在您的UITextView上调用caretRectForPosition
  • 创build一个CGRectvariables,并最初将CGRectZero存储在其中。
  • 在你的caretRectForPosition: textViewDidChange:方法中,调用caretRectForPosition:通过传递UITextPosition
  • 将其与CGRectvariables中存储的当前值进行比较。 如果caretRect的新y值大于最后一个,则意味着已经达到新的一行。

示例代码:

 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; } 

另外,您应该在这里阅读UITextInput协议参考的文档。 这是神奇的,我告诉你。

让我知道如果你有任何其他的问题。

对于Swift使用这个

 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 } 

你可以使用UITextViewDelegate

 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText: (NSString *)text { BOOL newLine = [text isEqualToString:@"\n"]; if(newLine) { NSLog(@"User started a new line"); } return YES; } 

Swift 3

接受的答案和迅捷的版本工作正常,但这里是一个懒惰的人在那里的Swift 3版本。

 class CustomViewController: UIViewController, UITextViewDelegate { let textView = UITextView(frame: .zero) var previousRect = CGRect.zero override func viewDidLoad(){ textView.frame = CGRect( x: 20, y: 0, width: view.frame.width, height: 50 ) textView.delegate = self view.addSubview(textView) } func textViewDidChange(_ textView: UITextView) { let pos = textView.endOfDocument let currentRect = textView.caretRect(for: pos) if previousRect != CGRect.zero { if currentRect.origin.y > previousRect.origin.y { print("new line") } } previousRect = currentRect } } 

你需要获得文本的高度,而不是宽度。 使用sizeWithFont:constrainedToSize:lineBreakMode:如果您需要支持iOS 6或更低版本)或使用boundingRectWithSize:options:attributes:context:如果您只支持iOS 7。