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