检查 UITextView 中的文本是否由于自动换行而转到新行 [英] Check if text in UITextView went to new line due to word wrap
问题描述
如何检查 UITextView
中的文本是否由于自动换行而转到下一行?
How can I check if the text in a UITextView
went to the next line due to word wrap?
我目前有代码来检查用户是否输入了新行(从键盘).
I currently have code to check if the user enters a new line (from the keyboard).
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
if ( [text isEqualToString:@"\n"] ) {
...
}
return YES;
}
推荐答案
您可以使用 UITextView 的 contentSize.height 属性来确定您的 textview 有多高".然后,您可以除以 lineHeight 来计算行数.@nacho4d 提供了这行漂亮的代码来做到这一点:
You can use the contentSize.height property of UITextView to determine how 'tall' your textview is. You can then divide by the lineHeight to figure out the number of lines. @nacho4d provided this nifty line of code that does just that:
int numLines = textView.contentSize.height/textView.font.lineHeight;
有关更多信息,请参阅此问题:如何在uitextview中读取行数
Refer to this question for more info: How to read number of lines in uitextview
因此,您可以在 -textViewDidChange: 中执行类似操作,以检查行更改.
So you could do something like this inside -textViewDidChange: in order to check for a line change.
int numLines = textView.contentSize.height / textView.font.lineHeight;
if (numLines != numLinesInTextView){
numLinesInTextView = numLines;//numLinesInTextView is an instance variable
//then do whatever you need to do on line change
}
这篇关于检查 UITextView 中的文本是否由于自动换行而转到新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!