简体   繁体   English

UITextView iOS 7的行数

[英]UITextView number of lines iOS 7

In iOS 6 I used this code to get the number of lines in the UITextView : 在iOS 6中,我使用此代码获取UITextView的行数:

int numLines = textView.contentSize.height / textView.font.lineHeight;

But this is not working in iOS 7. How do I get the total number of lines of the UITextView in iOS 7? 但这在iOS 7中不起作用。如何获得iOS 7中UITextView的总行数?

You can use something like this. 你可以使用这样的东西。 It's low performance but this is what I could figure till now. 这是低性能,但这是我现在可以想到的。

NSString *string=textView3.text;
NSArray *array=[string componentsSeparatedByString:@"\n"];
NSLog(@"%d",array.count);

You can do this with the UITextInputTokenizer / UITextInput protocol methods of UITextView. 您可以使用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 (??)

( GIST ) GIST

you can pass the String and textView to this method and it will return the current number rows in this textview even if the user pressed new line: 您可以将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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM