美文网首页实用轮子iOS Developer
iOS-固定宽度下长字符串的分行

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

作者: 西蒙SIMON | 来源:发表于2017-02-24 00:45 被阅读102次

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

    #import "NSString+Lines.h"
    #import <CoreText/CoreText.h>
    
    @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-固定宽度下长字符串的分行

        本文链接:https://www.haomeiwen.com/subject/abpiwttx.html