iOS-固定宽度下长字符串的分行

需求:在固定宽度内,返回一个字符串需要显示的每行字符串
思路:Foundation框架并没有提供快相关API来解决这个问题,但是CoreText有,因为可能基础的应用CoreText应用不多,这里给出个sample,有兴趣的可以研究下:

#import "NSString+Lines.h"
#import 

@implementation NSString (Lines)

- (NSArray *)getSeparatedLinesWithFont:(UIFont *)font width:(CGFloat)width {
    CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:self];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
    
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0, 0, width, 100000));
    
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    
    for (id line in lines)
    {
        CTLineRef lineRef = (__bridge CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        
        NSString *lineString = [self substringWithRange:range];
        [linesArray addObject:lineString];
    }
    return (NSArray *)linesArray;

}

@end

你可能感兴趣的:(iOS-固定宽度下长字符串的分行)