检测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一个
CGRect
variables,并最初将CGRectZero
存储在其中。 - 在你的
caretRectForPosition:
textViewDidChange:
方法中,调用caretRectForPosition:
通过传递UITextPosition
。 - 将其与
CGRect
variables中存储的当前值进行比较。 如果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。
- 具有多个项目的工作区或具有多个目标的一个项目?
- maxConcurrentOperationCount的NSOperationQueue的默认值
- AVAssetExportSession失败 – 合并2个WAV文件(iOS7)
- 获取失败块AFNetworking 3.0上的responseObject
- 在iOS 7中使用相机时,应用程序因内存压力而终止
- 使用AVCaptureAudioDataOutputSampleDelegate无法播放通过语音录制的audio
- Flash CS5.5:使用iPhone上的CameraUI捕捉照片时,照片会旋转
- afnetworking 3.0迁移:如何使用标题和HTTP正文进行POST
- 计算可变参数的移动平均值