0

I can't just split the string with "\n" and count the lines that way since word wrapping occurs dynamically.

What I need is a function that returns the lines (strings) from UITextView at that point in time.

Edit: this is not a duplicate of Counting the number of lines in a UITextView, lines wrapped by frame size , since I need contents of lines, not just line count.

Sarp Başaraner
  • 505
  • 7
  • 17
  • Yes, it _is_ a duplicate. If you look at that answer and think about the technique used, you will see that you also get the line fragments that give you the range information for each wrapped line. – matt Jun 14 '19 at 16:39

1 Answers1

1

Inspired by this answer. It appears, that you need to calculate word wrapping by yourself. Here is a simple example:

@interface UITextView (Lines)

- (NSArray*) textLines;

@end

@implementation UITextView (Lines)

- (NSArray*) textLines{
    NSMutableArray *result = @[].mutableCopy;

    NSArray *input = [self.text componentsSeparatedByString:@" "];

    NSDictionary *attributes = @{NSFontAttributeName:self.font};
    CGFloat maxWidth = self.frame.size.width - self.textContainer.lineFragmentPadding*2;
    NSMutableString *currentLine = @"".mutableCopy;

    for (NSString *component in input) {
        NSString *componentCheck = [NSString stringWithFormat:@" %@",component];
        CGSize currentSize = [currentLine sizeWithAttributes:attributes];
        CGSize componentSize = [componentCheck sizeWithAttributes:attributes];
        if (currentSize.width + componentSize.width < maxWidth) {
            [currentLine appendString:componentCheck];
        }else{
            [result addObject:currentLine];
            currentLine = component.mutableCopy;
        }
    }

    return result;
}

@end
Perversio
  • 46
  • 6