UITextView number of lines iOS 7

随声附和 提交于 2020-01-02 03:15:11

问题


In iOS 6 I used this code to get the number of lines in the 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?


回答1:


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);



回答2:


You can do this with the UITextInputTokenizer/UITextInput protocol methods of UITextView.

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)




回答3:


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:

-(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;
}


来源:https://stackoverflow.com/questions/19123022/uitextview-number-of-lines-ios-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!