我尝试检测 UITextView 中的回车何时换行。我可以通过比较以后的总宽度和 UITextView 宽度来检测它:
CGSize size = [textView.text sizeWithAttributes:textView.typingAttributes];
if(size.width > textView.bounds.size.width)
NSLog (@"New line");
但它无法正常工作,因为 -sizeWithAttributes:textView
仅返回字母宽度而没有缩进宽度。请帮忙解决这个问题。
最佳答案
我会这样做:
- 获取最后一个字符的
UITextPosition
。 - 在您的
UITextView
上调用caretRectForPosition
。 - 创建一个
CGRect
变量并在其中初始存储CGRectZero
。 - 在您的
textViewDidChange:
方法中,通过传递UITextPosition
调用caretRectForPosition:
。 - 将它与存储在
CGRect
变量中的当前值进行比较。如果 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
协议(protocol)引用文档here .这很神奇,我告诉你。
如果您对此有任何其他问题,请告诉我。
关于ios - 检测换行符在 UITextView 中开始的时刻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20008713/