<分区>
我不能只用“\n”分割字符串并计算行数,因为自动换行是动态发生的。
我需要的是一个函数,它可以在那个时间点从 UITextView 返回行(字符串)。
编辑:这不是 Counting the number of lines in a UITextView, lines wrapped by frame size 的副本,因为我需要行的内容,而不仅仅是行数。
<分区>
我不能只用“\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/