在 iOS 6 中,我使用此代码来获取以下代码中的行数UITextView
:
int numLines = textView.contentSize.height / textView.font.lineHeight;
但这在 iOS 7 中不起作用。如何获取 iOS 7 中 UITextView 的总行数?
在 iOS 6 中,我使用此代码来获取以下代码中的行数UITextView
:
int numLines = textView.contentSize.height / textView.font.lineHeight;
但这在 iOS 7 中不起作用。如何获取 iOS 7 中 UITextView 的总行数?
你可以使用这样的东西。它的性能很低,但这是我到目前为止所能想到的。
NSString *string=textView3.text;
NSArray *array=[string componentsSeparatedByString:@"\n"];
NSLog(@"%d",array.count);
你可以使用UITextView的UITextInputTokenizer
/协议方法来做到这一点。UITextInput
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextPosition *pos = textView.endOfDocument; int lines = 0;
while (true){
UITextPosition *lineEnd = [tokenizer positionFromPosition:pos toBoundary:UITextGranularityLine inDirection:UITextStorageDirectionBackward];
if([textView comparePosition:pos toPosition:lineEnd] == NSOrderedSame){
pos = [tokenizer positionFromPosition:lineEnd toBoundary:UITextGranularityCharacter inDirection:UITextStorageDirectionBackward];
if([textView comparePosition:pos toPosition:lineEnd] == NSOrderedSame) break;
continue;
}
lines++; pos = lineEnd;
}
//lines--; // Compensation for extra line calculated (??)
(要点)
您可以将 String 和 textView 传递给此方法,即使用户按下换行符,它也会返回此 textview 中的当前行数:
-(int)numberOfRows:(NSString *)string inView:(UITextView*)txtView
{
CGSize maximumLabelSize = CGSizeMake(MAXFLOAT , MAXFLOAT);
NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin;
NSString *new = [string stringByReplacingOccurrencesOfString: @"\n" withString:@" "];
NSDictionary *attr = @{NSFontAttributeName: [UIFont fontWithName:urFont size:urSize]};
CGRect bounds = [new boundingRectWithSize:maximumLabelSize
options:options
attributes:attr
context:nil];
CGSize viewSize = bounds.size;
int row = floor(txtView.contentSize.height / viewSize.height ) ;
return row;
}