换行后如何在UITextView中获取行?

时间:2019-06-12 20:21:37

标签: ios objective-c swift uikit uitextview

由于自动换行,我不能只用“ \ n”分割字符串并计算行数。

我需要的是一个可以在该时间点从UITextView返回行(字符串)的函数。

编辑:这不是Counting the number of lines in a UITextView, lines wrapped by frame size的重复,因为我需要行的内容,而不仅仅是行数。

1 个答案:

答案 0 :(得分:1)

this answer的启发。 看来,您需要自己计算自动换行。 这是一个简单的示例:

@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