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

Ios 如何在换行后在UITextView中获取行?,ios,objective-c,swift,uikit,uitextview,Ios,Objective C,Swift,Uikit,Uitextview,我不能用“\n”拆分字符串并按这种方式计算行数,因为换行是动态发生的 我需要的是一个函数,它在该时间点从UITextView返回行(字符串) 编辑:这不是的复制品,因为我需要行的内容,而不仅仅是行数。灵感来源于。 看起来,您需要自己计算单词包装。 下面是一个简单的例子: @interface UITextView (Lines) - (NSArray*) textLines; @end @implementation UITextView (Lines) - (NSArray*) tex

我不能用“\n”拆分字符串并按这种方式计算行数,因为换行是动态发生的

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

编辑:这不是的复制品,因为我需要行的内容,而不仅仅是行数。

灵感来源于。 看起来,您需要自己计算单词包装。 下面是一个简单的例子:

@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
@接口UITextView(行)
-(NSArray*)文本行;
@结束
@实现UITextView(行)
-(NSArray*)文本行{
NSMutableArray*结果=@[].mutableCopy;
NSArray*输入=[self.text组件由字符串分隔:@”“];
NSDictionary*attributes=@{NSFontAttributeName:self.font};
CGFloat maxWidth=self.frame.size.width-self.textContainer.lineFragmentPadding*2;
NSMutableString*currentLine=@“。mutableCopy;
for(输入中的NSString*组件){
NSString*componentCheck=[NSString stringWithFormat:@“%@”,component];
CGSize currentSize=[currentLine SizeWithatAttributes:attributes];
CGSize componentSize=[componentCheck SizeWithatAttributes:attributes];
if(currentSize.width+componentSize.width
是的,它是重复的。如果您查看该答案并考虑所使用的技术,您将看到您还获得了线条片段,这些片段为您提供了每个包装线条的范围信息。