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

标签 ios objective-c swift uikit uitextview

我不能只用“\n”分割字符串并计算行数,因为自动换行是动态发生的。

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

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

最佳答案

灵感来自 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

关于ios - 换行后如何在 UITextView 中获取行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56569831/

相关文章:

iphone - nil 和 NULL 的区别

ios - JSONEncoder 去除尾随零

ios - 根据多个点的经纬度获取地址

objective-c - 将我的项目从 Objective-C xcode 5.1 转移到 SWIFT 和 xcode 6

swift - CLLocationManager.authorizationStatus() 总是 CLAuthorizationStatus.NotDetermined with swift&objC app

ios - 无法在 UIPickerView 中转换异常类型的值

ios - 有没有办法在iOS上生成二维码图片

objective-c - Cocos2d :Add uilabel in scene

objective-c - 释放以正确方式返回的对象?

ios - 过滤搜索多个词,iOS,Swift